Python Collections
PYTHON COLLECTIONS
LIST TRAVERSAL
Example of traversing a list using a for loop:
my_list = [1, 2, 3, 4] for item in my_list: print(item)
LIST MEMBERSHIP
Check if an item is in a list:
my_list = [1, 2, 3, 4] print(3 in my_list) # True print(5 in my_list) # False print(5 not in my_list) # True
LIST ASSIGNMENTS AND EQUIVALENCE
Assigning lists:
Using the assignment operator
=does not create a copy, both variables will refer to the same list.
Checking equivalence:
Use
==to check if two lists have the same content.
Example:
list1 = [1, 2, 3] list2 = list1 # Both refer to the same list list3 = [1, 2, 3] print(list1 == list3) # True (same content) print(list1 is list3) # False (different objects)
LIST BOUNDS
List bounds refer to the valid index range for a list.
Accessing out-of-range index raises an
IndexError:my_list = [1, 2, 3] print(my_list[2]) # Valid index # print(my_list[5]) # Raises IndexError
SLICING
Slicing allows accessing a part of a list by specifying start and end index:
my_list = [0, 1, 2, 3, 4, 5] sliced_list = my_list[1:4] # Elements from index 1 to 3 print(sliced_list) # Output: [1, 2, 3]
LIST METHODS
Common List Methods:
append(x): Add an item to the end of the list.extend(L): Extend the list by appending all items in the given list.insert(i, x): Insert an item at a given position.remove(x): Remove the first item whose value isx.
Additional Methods:
pop([i]): Remove the item at the given position and return it; if no index is specified,pop()returns the last item.index(x): Return the index of the first item whose value isx.count(x): Return the number of timesxappears in the list.sort(): Sort items of the list in place.reverse(): Reverse the elements of the list in place.
USING LISTS AS STACKS
Stacks follow Last-In-First-Out (LIFO) principle:
stack = [3, 4, 5] stack.append(6) stack.pop() # Removes 6
USING LISTS AS QUEUES
Queues follow First-In-First-Out (FIFO) principle:
queue = ["Eric", "John", "Michael"] queue.append("Terry") # Terry arrives queue.pop(0) # Removes "Eric"
FILTER(), MAP(), AND REDUCE()
Example of using
filterfunction:def f(x): return x % 2 != 0 and x % 3 != 0 print(filter(f, range(2, 25))) # Outputs: [5, 7, 11, 13, 17, 19, 23]Using
reduce:from functools import reduce def add(x, y): return x + y print(reduce(add, range(1, 11))) # Outputs: 55
LIST COMPREHENSIONS
Provide a concise way to create lists without using map, filter, and/or lambda:
Example:
squared_numbers = [(x, x**2) for x in range(5)] # Outputs: [(0,0),(1,1),(2,4),(3,9),(4,16)]
BASIC LIST OPERATIONS
Common operations include:
Length:
len([4, 2, 3])-> 3Concatenation:
[4, 2, 3] + [1, 5, 6]Membership:
3 in [4, 2, 3]
IMPORTANT METHODS AND FUNCTIONS OF LIST
list.append(): Add an item at end of a list.list.extend(): Add multiple items at end of a list.list.remove(): Remove an item from a list.list.pop(): Remove an item at a defined index.len(list): Return total length of the list.
DICTIONARIES
Introduction:
A dictionary is a collection of key-value pairs.
Each key is unique and accesses values by keys, not indices.
Key Features:
Mutable: Change values, add new key-value pairs.
Unordered (before Python 3.7): Keys did not maintain order.
Keys must be immutable data types.
OPERATIONS ON DICTIONARIES
Accessing elements:
print(my_dict["age"])Adding elements:
my_dict["job"] = "Engineer"Deleting elements:
del my_dict["age"]
DICTIONARY METHODS
Common Methods:
dict.clear(): Removes all elements of a dictionary.dict.copy(): Returns a shallow copy of a dictionary.dict.items(): Returns key-value tuple pairs.dict.keys(): Returns a list of dictionary's keys.
TUPLES
A sequence of immutable objects, created using parentheses:
Example:
tup1 = (‘comp sc', ‘info practices', 2017, 2018)
SETS
Introduction:
A set is a collection of unordered, unique elements.
Useful for eliminating duplicates and performing set operations.
Example:
my_set = {1, 2, 3, 4, 4} # Output: {1, 2, 3, 4}
STRING MANIPULATION
Strings are sequences of characters and are immutable.
Common operations include slicing and methods:
Example:
name = "Alice" print(name[0]) # Outputs: A
EXCEPTIONS
Exceptions are errors detected during execution.
Use
try,except,else, andfinallyto handle exceptions.
Basic Syntax:
try: risky_operation() except SomeException: handle_error() else: success_operation() finally: cleanup_operation()
PRACTICE EXERCISES
Write a program to perform Linear Search in a list.
Write a program to find the Frequency of an element in a list.
Find the sum of all elements in a list.