1. Python Data Structures: Lists, Tuples, Dictionaries, and Sets
Advanced List Methods and Indexing Operations
List Creation and Modification
Lists can be initialized as empty structures or with predefined elements using square brackets .
The
appendfunction adds a single element to the absolute end of a list.The
popoperation removes and returns the last element in the sequence.Specific items can be removed using the
deleteoperation or by slicing them out.
Slicing and Sequence Retrieval
Slicing uses colon operators to select a range of the list, creating a new copy of that specific part.
Core List Functionalities
Remove: Searches for the first instance of a specific value and removes it from the list. If the item is present multiple times, only the first instance is deleted. Attempting to remove a non-existent item results in an error.
Insert: Requires a specific index position and a value. The syntax is
insert(index, value). The existing data at that index and everything to its right is shifted one position further.Index: A command used to locate the specific index position of a value.
Extend: Lengthens a list by joining another list to the end of the original.
Insert Command Behavior with Boundary Cases
Out-of-Bound Indices: If the index provided for an
insertoperation is larger than the current maximum index, Python does not produce an error. Instead, it treats the command as anappendand adds the value to the end of the list.Negative Indexing: Inserting at a negative index (e.g., ) targets a position relative to the end. For example, if a list is
[1, 2, 3, a, a], its negative third index is . Usinginsert(-3, 'y')shifts the element to the right and places just before it, resulting in[1, 2, y, 3, a, a].Large Negative Indices: If a negative index exceeds the length of the list (e.g., for a 7-item list), Python adds the element to the very front of the sequence without creating empty spaces, maintaining a contiguous sequence.
Deleting Objects versus Clearing Content
Using the
deletecommand on an individual index or a slice removes those specific items.Deleting the object itself (e.g.,
del a) erases the variable from the computer's memory, making it undefined and inaccessible for subsequent printing.To remove all contents while keeping the object active in memory, one can clear the contents to leave an empty list .
Tuples and Immutability
Definition and Syntax
Tuples are sequences similar to lists but are defined using parentheses instead of brackets.
The primary characteristic of a tuple is that it is immutable, meaning it cannot be modified, updated, or changed once created.
Use Cases for Tuples
Tuples provide data security for variables that should remain constant throughout a program's execution.
Type Determination and Evaluation Logic
Python interprets parentheses first as potential mathematical expressions before considering them as tuples.
Case 1:
type((1))returns<class 'int'>because the parentheses are seen as redundant mathematical markers around the integer .Case 2:
type((1,))returns<class 'tuple'>because the presence of a comma prevents it from being a simple mathematical expression, signaling to Python that it is a collection.Case 3:
type(())returns<class 'tuple'>as there is no numerical expression to evaluate.
Tuple Operations
Length: The
len()function returns the number of elements in the tuple.Extension: While a tuple cannot be modified, two tuples can be combined to generate a third, entirely new tuple (e.g.,
(1, 2, 3) + (4, 5, 6)becomes(1, 2, 3, 4, 5, 6)).Slicing: Portions of a tuple can be extracted to create a new object without altering the original.
Membership: The
inoperator checks if a specific value is present within the tuple.
Unpacking and Value Swapping
Tuple Unpacking: Multiple variables can be assigned at once in a single line (e.g.,
a, b, c = (1, 2, 3)). The number of variables on the left must match the length of the tuple on the right.Function Returns: Tuples allow functions to return multiple objects of different types simultaneously.
Variable Swapping: Tuples enable shorthand swapping without a temporary variable. The command
d, e = e, dcreates a temporary memory assignment automatically to switch the values of and .
Dictionary Mappings and Key-Value Pairs
Structure and Definition
Dictionaries are collections of objects stored as pairs of keys and values, defined using curly braces .
They function as a lexicographical mapping, similar to a physical dictionary where unique words (keys) correspond to specific meanings (values).
Requirements for Keys and Values
Keys: Must be immutable and hashable objects, such as strings, tuples, or integers. Mutable objects like lists or other dictionaries cannot serve as keys.
Values: Can be any object type, including numbers, strings, lists, or even nested dictionaries.
Accessing and Navigating Dictionaries
Dictionaries do not use numerical indexing (). Instead, values are accessed via their keys.
Keys function:
.keys()returns a view of all keys in the dictionary.Values function:
.values()returns a view of all values.Items function:
.items()returns the content as a list of tuples, where each tuple is a pair.
Safe Data Retrieval and Modification
Direct Access: Accessing a non-existent key via brackets (e.g.,
d['missing_key']) results in aKeyError, which crashes the program.Get Command:
.get(key, default)is a safer access method. If the key exists, it returns the value; if not, it returns aNoneobject or a specified default value without breaking the program.Set Default:
.setdefault(key, default)checks for a key. If it exists, it returns the value. If it does not exist, it creates a new entry with the key and the provided default value.Update: The
.update()method takes another dictionary or iterable of pairs and modifies the original dictionary, adding new keys or overwriting existing ones.
Removal of Dictionary Elements
Pop:
pop(key)removes the specific key-value pair and returns only the value.Popitem:
popitem()removes and returns the last-inserted key-value pair as a tuple.Clear:
clear()removes every element, leaving an empty dictionary.
Set Operations and Uniqueness
Definition of Sets
A set is a collection of unique items. It automatically removes any duplicate values provided during initialization.
Sets can be created using the
set()constructor or curly braces . When a dictionary is passed toset(), only the keys are used.
Characteristics and Ordering
Sets are unordered from a user-manipulation perspective (supporting no index placement), but Python often stores them in an ordered sequence internally (e.g., alphabetical for strings).
Individual elements of a set cannot be accessed or modified via indexing.
Mathematical Set Operations
Union: Combining all elements from two sets (Operator: or function:
.union()).Intersection: Extracting only elements common to both sets (Operator: or function:
.intersection()).Difference: Elements in set but NOT in set (Operator: or function:
.difference()).Symmetric Difference: Elements present in either set or , but not in both (Operator: ^ or function:
.symmetric_difference()).
Set Relationships
Subsets and Supersets: Relationships are checked using comparison operators.
>denotes a proper superset.>=denotes a superset (where the sets can be equal).These operations check membership of components, not the length of the sets.
Questions & Discussion
Question: For the
insertcommand, which number represents the position and which is the value?Answer: In the command
insert(1, 2), the number is the index position where the insertion occurs, and is the actual value being added.
Question: What happens if you use a negative index with the
insertcommand?Answer: The command identifies the item currently at that negative position, shifts it to the right, and inserts the new value in its place.
Question: If a negative index is larger than the array, does it just append it to the front?
Answer: Yes, it adds the element to the beginning of the sequence to maintain a contiguous list.
Question: Can you delete an object and then print it?
Answer: No. Deleting the object (e.g.,
del a) removes it from memory entirely. Trying to print it afterwards results in a name error stating the object is not defined.
Question: Is there a meaningful difference between
a, b, c = (1, 2, 3)anda, b, c = 1, 2, 3?Answer: Not significantly in execution. However, the first format (with parentheses) might represent unpacking a returned package or tuple from an external part of a program, while the second is intentional simultaneous assignment of three values.
Question: Does
name in dcheck values or keys?Answer: It checks the keys. Values are protected and cannot be directly accessed this way. To check for a value like 'Germany', one must use
Germany in d.values().
Question: Do we need a laptop for the pop quiz?
Answer: No, the quizzes are accessible via mobile devices or any available web-connected resource.