Wa0005.
Wa0005.
programming concepts. Here are your notes, packed with information, syntax, and examples:
Lists
Creating Lists: Lists are ordered, mutable sequences of items. You can create them in several
ways:
● Using square brackets []:
my_list = [1, 2, 3, 'hello', 3.14]
empty_list = []
Operations on Lists:
● Accessing elements (indexing): Use square brackets with the index (0-based).
Negative indexing accesses elements from the end.
my_list = [10, 20, 30, 40, 50]
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 50
● Membership testing: Check if an element exists using the in and not in operators.
my_list = ['apple', 'banana', 'cherry']
print('banana' in my_list) # Output: True
print('grape' not in my_list) # Output: True
● min(list): Returns the smallest element in the list (if elements are comparable).
print(min(numbers)) # Output: 5
● sum(list): Returns the sum of all elements in the list (if elements are numeric).
print(sum(numbers)) # Output: 50
● Queue (FIFO - First-In, First-Out): For efficient queue implementation, it's better to use
collections.deque because pop(0) on a standard list is an O(n) operation. However, for
basic understanding:
queue = []
queue.append('first')
queue.append('second')
queue.append('third')
print(queue) # Output: ['first', 'second', 'third']
print(queue.pop(0)) # Output: 'first'
print(queue) # Output: ['second', 'third']
print(queue.pop(0)) # Output: 'second'
print(queue) # Output: ['third']
# More efficient using deque:
from collections import deque
efficient_queue = deque()
efficient_queue.append('first')
efficient_queue.append('second')
efficient_queue.append('third')
print(efficient_queue.popleft()) # Output: 'first'
Nested Lists: Lists can contain other lists, creating nested structures (like matrices or
multi-dimensional arrays).
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(matrix[0]) # Output: [1, 2, 3]
print(matrix[1][2]) # Output: 6 (element at row 1, column 2)
Dictionaries
Creating Dictionaries: Dictionaries are unordered collections of key-value pairs. Keys must be
unique and immutable (strings, numbers, tuples).
● Using curly braces {}:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
empty_dict = {}
Operations on Dictionaries:
● Accessing values: Use the key in square brackets.
print(my_dict['name']) # Output: Alice
# Using .get() to avoid KeyError if the key doesn't exist
print(my_dict.get('age')) # Output: 30
print(my_dict.get('occupation')) # Output: None
print(my_dict.get('occupation', 'Not specified')) # Output: Not
specified
Dictionary Methods:
● keys(): Returns a view object that displays a list of all the keys in the dictionary.
print(my_dict.keys()) # Output: dict_keys(['name', 'age',
'city'])
● values(): Returns a view object that displays a list of all the values in the dictionary.
print(my_dict.values()) # Output: dict_values(['Alice', 30, 'New
York'])
● items(): Returns a view object that displays a list of all the key-value tuple pairs.
print(my_dict.items()) # Output: dict_items([('name', 'Alice'),
('age', 30), ('city', 'New York')])
● update(other_dict): Updates the dictionary with the key-value pairs from other_dict.
Existing keys are overwritten, new keys are added.
more_info = {'country': 'USA', 'zip': '10001'}
my_dict.update(more_info)
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001'}
● setdefault(key, default): If the key is in the dictionary, it returns its value. If not, it inserts
the key with the specified default value and returns default.
print(my_dict.setdefault('occupation', 'Not specified')) # Output:
Not specified
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001', 'occupation': 'Not specified'}
print(my_dict.setdefault('age', 35)) # Key exists, returns
existing value
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York',
'country': 'USA', 'zip': '10001', 'occupation': 'Not specified'}
Operations on Tuples:
● Accessing elements (indexing): Similar to lists.
print(my_tuple[0]) # Output: 1
print(my_tuple[-1]) # Output: 3.14
● index(value): Returns the index of the first occurrence of a value. Raises ValueError if the
value is not found.
print(my_tuple.index(3)) # Output: 3
Operations on Sets:
● Adding elements:
○ set.add(element): Adds a single element.
○ set.update(iterable): Adds multiple elements from an iterable (like a list or another
set).
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output (order may vary): {1, 2, 3, 4}
my_set.update([4, 5, 6])
print(my_set) # Output (order may vary): {1, 2, 3, 4, 5,
6}
● Removing elements:
○ set.remove(element): Removes the specified element. Raises KeyError if the
element is not found.
○ set.discard(element): Removes the element if it is present. Does not raise an error if
the element is not found.
○ set.pop(): Removes and returns an arbitrary element from the set. Raises KeyError
if the set is empty.
○ set.clear(): Removes all elements from the set.
● Set operations:
○ Union (| or set.union(other_set)): Returns a new set containing all elements from
both sets.
○ Intersection (& or set.intersection(other_set)): Returns a new set containing
elements common to both sets.
○ Difference (- or set.difference(other_set)): Returns a new set containing
elements in the first set but not in the second.
○ Symmetric Difference (^ or set.symmetric_difference(other_set)): Returns a
new set containing elements that are in either set, but not in both.
○ Subset (<= or set.issubset(other_set)): Checks if all elements of the first set are
present in the second set.
○ Superset (>= or set.issuperset(other_set)): Checks if all elements of the second
set are present in the first set.
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1 | set2) # Output (order may vary): {1, 2, 3,
4, 5, 6}