03 - List, Tuples & Dictionary
Table of contents
Lists
- A list in Python is a collection of items (or elements) that are ordered, mutable (can be modified), and allow duplicate values.
Key Features of Lists
Ordered: The items in a list are maintained in the order they are added.
Mutable: Lists can be modified (e.g., adding, removing, or changing elements).
Heterogeneous: A list can contain elements of different data types.
Duplicate Elements: Lists can have duplicate values.
Creating Lists
Empty List:
my_list = []
List with Elements:
my_list = [1, 2, 3, 4]
List with Mixed Data Types:
my_list = [1, "hello", 3.14, True]
List from a Function (e.g.,
range
):my_list = list(range(5)) # [0, 1, 2, 3, 4]
Accessing Elements in a List
Using Index:
my_list = [10, 20, 30, 40] print(my_list[0]) # 10 (First element) print(my_list[-1]) # 40 (Last element)
Slicing (more on this below):
print(my_list[1:3]) # [20, 30] print(my_list[:2]) # [10, 20] print(my_list[2:]) # [30, 40] print(my_list[::3]) # [10, 40]
Modifying a List
Changing Elements:
my_list = [10, 20, 30] my_list[1] = 25 # Update second element print(my_list) # [10, 25, 30]
Adding Elements:
Using
append()
(Adds an item to the end):my_list.append(40)
Using
insert()
(Adds an item at a specific position):my_list.insert(1, 15) # Insert 15 at index 1
Removing Elements:
Using
remove()
(Removes the first occurrence of a value):my_list.remove(20)
Using
pop()
(Removes and returns an item at a specific index):last_item = my_list.pop() # Removes last element
Using
del
(Deletes an element):del my_list[1] # Delete second element
Sorting and Reversing the List:
Using
sort()
: Sorts the elements of a list in place (modifying the original list). By default, it sorts the elements in ascending order.sort()
vssorted()
sort()
modifies the original list.sorted()
returns a new sorted list without modifying the original list.
list.sort(key=None, reverse=False)
numbers = [5, 2, 9, 1, 7]
numbers.sort() # Output: [1, 2, 5, 7, 9]
numbers.sort(reverse=True) # Output: [9, 7, 5, 2, 1]
sorted_numbers = sorted(numbers) # Output: [9, 7, 5, 2, 1]
Using
reverse()
: Reverses the order of the elements in the list in place (modifying the original list). It does not sort the elements but simply flips their order.numbers.reverse() # Output: [5, 4, 3, 2, 1]
Clearing the List:
my_list.clear()
List Operations
Concatenation:
list1 = [1, 2] list2 = [3, 4] result = list1 + list2 # [1, 2, 3, 4]
Repetition:
repeated_list = [1, 2] * 3 # [1, 2, 1, 2, 1, 2]
Membership Testing (Finding in List):
print(10 in [10, 20, 30]) # True print(40 not in [10, 20, 30]) # True
List Comprehensions
A concise way to create lists using a single line of code.
[expression for item in iterable if condition]
Example:
squared_numbers = [x**2 for x in range(5)] # [0, 1, 4, 9, 16] even_numbers = [x for x in range(10) if x % 2 == 0] # [0, 2, 4, 6, 8]
Slicing a List
Slicing in Python allows you to extract a portion (or subsequence) of a list by specifying a range of indices.
list[start:stop:step]
start
(Optional): The index to start slicing (inclusive). Default is0
.stop
: The index to stop slicing (exclusive). Required unless slicing is done for the entire list.step
(Optional): The step size or interval between indices. Default is1
.
Example:
my_list = [10, 20, 30, 40, 50] # Slice from index 1 to 4 (stop is exclusive) print(my_list[1:4]) # Output: [20, 30, 40] # Slice from the beginning to index 3 print(my_list[:3]) # Output: [10, 20, 30] # Slice the entire list print(my_list[:]) # Output: [10, 20, 30, 40, 50] # Slice the last three elements print(my_list[-3:]) # Output: [30, 40, 50] # Slice all elements except the last one print(my_list[:-1]) # Output: [10, 20, 30, 40] # Slice from the third last to the second last element print(my_list[-3:-1]) # Output: [30, 40] # Slice with a step of 2 print(my_list[::2]) # Output: [10, 30, 50] # Reverse the list print(my_list[::-1]) # Output: [50, 40, 30, 20, 10] copy = my_list[:] # Creates a shallow copy
2D and 3D Lists
2D Lists (Two-Dimensional Lists)
A 2D list is a list where each element is itself a list. It’s a table or matrix with rows and columns.
# A 2x3 matrix (2 rows, 3 columns) matrix = [ [1, 2, 3], [4, 5, 6] ]
3D Lists (Three-Dimensional Lists)
A 3D list is a list of 2D lists. It can represent a collection of matrices or tables.
# A 2x3x2 structure (2 matrices, each with 3 rows and 2 columns) tensor = [ [ [1, 2], [3, 4], [5, 6] ], [ [7, 8], [9, 10], [11, 12] ] ]
Common List Methods
Method | Description |
append(item) | Adds an item to the end of the list. |
extend(iterable) | Extends the list by appending elements from an iterable. |
insert(index, item) | Inserts an item at a specified position. |
remove(item) | Removes the first occurrence of a value. |
pop([index]) | Removes and returns an element at the index. |
clear() | Removes all elements from the list. |
index(item) | Returns the index of the first occurrence of a value. |
count(item) | Returns the number of times a value appears. |
sort([key], reverse) | Sorts the list in ascending or descending order. |
reverse() | Reverses the elements of the list. |
Tuples
A tuple in Python is a collection of ordered, immutable elements.
Tuples are similar to lists but with the key difference that their contents cannot be changed (immutable).
# Empty tuple empty_tuple = () # Tuple with one element (note the comma is required) single_element_tuple = (42,) # Tuple with multiple elements multiple_elements_tuple = (1, 2, 3) # Tuple without parentheses no_parentheses = 4, 5, 6
Tuple Properties
Immutable: You cannot change, add, or remove elements after a tuple is created.
my_tuple = (1, 2, 3) my_tuple[0] = 10 # Error: TypeError
Ordered: The order of elements in a tuple is preserved.
Heterogeneous: A tuple can contain elements of different types.
mixed_tuple = (1, "hello", 3.14, True)
Tuple Methods
- Tuples have limited built-in methods compared to lists because they are immutable.
Common Methods
count()
: Returns the number of occurrences of a value.index()
: Returns the first index of a value.pythonCopy codemy_tuple = (1, 2, 3, 2, 2) # Count occurrences of 2 print(my_tuple.count(2)) # Output: 3 # Find the index of the first occurrence of 2 print(my_tuple.index(2)) # Output: 1
Tuples vs Lists
Feature | Tuple | List |
Mutability | Immutable | Mutable |
Syntax | (1, 2, 3) | [1, 2, 3] |
Performance | Faster (less memory overhead) | Slower (more memory overhead) |
Use Case | Fixed, unchangeable data | Dynamic, changeable data |
Dictionary
A dictionary in Python is an ordered, mutable collection of key-value pairs.
Each key is unique and is used to access the associated value.
Creating a Dictionary
# Empty dictionary
empty_dict = {}
# Dictionary with key-value pairs
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Creating a dictionary using the dict() function
person = dict(name="Bob", age=30, city="London")
print(person) # Output: {'name': 'Bob', 'age': 30, 'city': 'London'}
Accessing Dictionary Elements
Using Keys
my_dict = {"name": "Alice", "age": 25} # Access value using a key print(my_dict["name"]) # Output: Alice # Access value with `get()` (preferred for avoiding KeyError) print(my_dict.get("age")) # Output: 25
KeyError vs.
get()
# Using `[]` results in KeyError # print(my_dict["city"]) # KeyError # Using `get()` returns `None` (or a default value if specified) print(my_dict.get("city", "Not Found")) # Output: Not Found
Adding, Updating, and Removing Elements
Adding or Updating
my_dict = {"name": "Alice"} # Add a new key-value pair my_dict["age"] = 25 print(my_dict) # Output: {'name': 'Alice', 'age': 25} # Update an existing key my_dict["age"] = 30 print(my_dict) # Output: {'name': 'Alice', 'age': 30}
Removing
my_dict = {"name": "Alice", "age": 25, "city": "New York"} # Remove a key using `del` del my_dict["city"] print(my_dict) # Output: {'name': 'Alice', 'age': 25} # Remove a key using `pop()` age = my_dict.pop("age") print(age) # Output: 25 print(my_dict) # Output: {'name': 'Alice'} # Remove all items with `clear()` my_dict.clear() print(my_dict) # Output: {}
Dictionary Methods
Method | Description |
keys() | Returns a view object of all keys. |
values() | Returns a view object of all values. |
items() | Returns a view object of all key-value pairs. |
get(key, default) | Returns the value of a key, or a default value. |
update(other_dict) | Updates the dictionary with another dictionary. |
pop(key) | Removes a key and returns its value. |
popitem() | Removes and returns the last key-value pair. |