LISTS AND DICTIONARIES
Introduction to Lists
A list is an ordered, mutable sequence of compound data types enclosed in square brackets [] and separated by commas. Lists support heterogeneous elements, meaning they can store integers, floats, strings, tuples, or even nested lists. List indexing supports forward zero-based indexing from to and reverse negative indexing from to . Accessing an invalid index raises an IndexError. Because lists are mutable, their elements can be modified, replaced, added, or deleted in place without altering the memory identity of the list object.
List Operations
List concatenation using the + operator joins two lists together to form a new list object, requiring both operands to be lists. Repetition using the * operator replicates list elements a specified integer number of times. The membership operators in and not in evaluate whether a specific element exists inside a given list. Slicing with the syntax list[start:stop:step] extracts a contiguous sub-list. In slicing, a missing start defaults to , a missing stop defaults to , and a missing step defaults to . Reversing a list via slicing is achieved using list[::-1].
Traversing a List
Traversing a list can be accomplished through item-based iteration or index-based iteration. In item-based iteration, a for loop directly accesses each element using for item in list1: print(item). In index-based iteration, a loop iterates over valid indices using for i in range(len(list1)): print(list1[i]) to access elements by index.
Essential Built-in Functions and List Methods
Several built-in functions and methods facilitate working with lists.
The
len(list)function returns the total element count, whilelist(seq)converts a sequence to a list or creates an empty list.Elements can be added using
append(x)to add a single element to the end,extend(iterable)to append all items of an iterable individually,or
insert(i, x)to insert item at a specified index . Searching and counting are supported viacount(x)to return total occurrences of ,index(x)to return the index of the first occurrence of (raising aValueErrorif absent).Item removal is handled by
remove(x)to delete the first occurrence of (raising aValueErrorif absent),or
pop([i])to remove and return the element at index , defaulting to the last element. Ordering can be altered usingreverse()to flip elements in place,sort(reverse=False)to sort items in place, orsorted(list)to return a new sorted list without modifying the original.Additionally,
min(list),max(list), andsum(list)return the minimum value, maximum value, and arithmetic sum of the elements respectively.
Introduction to Dictionaries
A dictionary is an ordered, mutable mapping of key-value pairs written as key: value enclosed within curly braces {}. Keys must be unique and belong to immutable data types such as numbers, strings, or tuples. In contrast, values can be duplicated and belong to any data type. Elements inside a dictionary are accessed using key names via dict[key], and attempting to access a non-existent key raises a KeyError. Membership operators in and not in evaluate the existence of keys only. Dictionaries are mutable, meaning key-value pairs can be added or updated directly through assignment using dict[key] = value.
Traversing a Dictionary
Traversing a dictionary can be performed by iterating over keys or key-value pairs. Key iteration uses for key in dict1: print(key, ':', dict1[key]) to access keys and their associated values. Key-value pair iteration utilizes for key, value in dict1.items(): print(key, ':', value) to retrieve both components simultaneously during iteration.
Key Dictionary Functions & Methods
Dictionaries provide various built-in functions and methods for manipulation. The len(dict) function returns the count of key-value pairs, and dict() constructs a dictionary from sequence pairs. The keys(), values(), and items() methods return views of all keys, values, and key-value tuple pairs respectively. The get(key) method retrieves the value for a specified key or returns None if the key does not exist. Updating and deleting content can be done using update(dict2) to merge key-value pairs from dict2 into the target dictionary, clear() to delete all items, or del dict[key] to delete a specific item by its key.