Instructor : Seyed Sadjad Abedi-Shahri
Python provides several built-in data structures that allow you to organize and store data efficiently. In this session, we’ll explore data structures in Python.
Lists are ordered collections of items, which can be of different data types. They are mutable, meaning you can modify, add, or remove elements after creating the list.
Lists are defined using square brackets []
and elements are separated by commas.
1fruits = ["apple", "banana", "cherry"]
2numbers = [1, 2, 3, 4, 5]
3mixed = [1, "apple", 3.14, True]
Lists support various operations, such as indexing, slicing, concatenation, and more.
1fruits = ["apple", "banana", "cherry"]
2
3print(len(fruits)) # Get the length of the list (Output: 3)
4print(fruits[0]) # Access the first element (Output: "apple")
5print(fruits[-1]) # Access the last element (Output: "cherry")
6print(fruits[1:3]) # Get a slice (from index 1 to 3) (Output: ["banana", "cherry"])
7fruits.append("orange") # Add an element to the end
8fruits.insert(1, "kiwi") # Insert an element at a specific index
9fruits.remove("banana") # Remove the first occurrence of an element
10fruits.pop(2) # Remove the element at a specific index
Lists are versatile and commonly used for storing and manipulating collections of data in Python.
Tuples are ordered collections of items, similar to lists, but they are immutable, meaning you cannot modify, add, or remove elements after creating the tuple.
Tuples are defined using parentheses ()
and elements are separated by commas.
1point = (3, 4)
2person = ("John", 32, "Programmer")
3empty_tuple = ()
Alternatively, you can create tuples without parentheses if there is a comma separating the elements.
1point = 3, 4
2single_element_tuple = 1, # Note the trailing comma
Although tuples are immutable, you can perform various operations on them, such as indexing, slicing, and concatenation.
1person = ("John", 32, "Programmer")
2
3print(len(person)) # Get the length of the tuple (Output: 3)
4print(person[0]) # Access the first element (Output: "John")
5print(person[-1]) # Access the last element (Output: "Programmer")
6print(person[1:3]) # Get a slice (from index 1 to 3) (Output: (32, "Programmer"))
Tuples are commonly used for storing and handling collections of related but immutable data, such as coordinates, database records, or configuration settings.
Sets are unordered collections of unique elements. They are mutable, meaning you can add or remove elements after creating the set. Sets are useful for performing mathematical operations like union, intersection, and difference on collections of elements.
Sets are defined using curly braces {}
or the set()
function.
1fruits = {"apple", "banana", "cherry"}
2numbers = set([1, 2, 3, 4, 4, 5]) # Duplicates are automatically removed
Sets support various operations, such as adding and removing elements, performing set operations, and more.
1fruits = {"apple", "banana", "cherry"}
2
3fruits.add("orange") # Add an element to the set
4fruits.remove("banana") # Remove an element from the set
5fruits.discard("kiwi") # Remove an element if it exists (no error if not)
6
7numbers = {1, 2, 3, 4, 5}
8even_numbers = {2, 4, 6, 8}
9
10print(numbers | even_numbers) # Union (Output: {1, 2, 3, 4, 5, 6, 8})
11print(numbers & even_numbers) # Intersection (Output: {2, 4})
12print(numbers - even_numbers) # Difference (Output: {1, 3, 5})
Sets are useful for removing duplicates, performing mathematical operations on collections, and maintaining an unordered collection of unique elements.
Dictionaries are unordered collections of key-value pairs. They are mutable, meaning you can add, modify, or remove key-value pairs after creating the dictionary. Dictionaries are useful for storing and retrieving data based on keys.
Dictionaries are defined using curly braces {}
with key-value pairs separated by colons.
1person = {"name": "John", "age": 32, "occupation": "Programmer"}
2empty_dict = {}
Dictionaries support various operations, such as accessing, adding, modifying, and removing key-value pairs.
1person = {"name": "John", "age": 32, "occupation": "Programmer"}
2
3print(person["name"]) # Access the value associated with the "name" key (Output: "John")
4person["age"] = 33 # Modify the value associated with the "age" key
5person["location"] = "USA" # Add a new key-value pair
6del person["occupation"] # Remove a key-value pair
7for key, value in person.items():
8 print(f"{key}: {value}") # Iterate over key-value pairs
Dictionaries are used for storing and retrieving data based on keys, representing structured data like objects or records, and implementing efficient lookup and retrieval operations.
List comprehensions in Python provide a concise and efficient way to create lists from existing iterables (such as lists, tuples, or strings) based on specific conditions or transformations. They offer a more readable and expressive syntax compared to traditional for
loops and can often lead to more compact and optimized code.
The basic syntax for a list comprehension is as follows:
1new_list = [expression for item in iterable]
new_list
: The new list created by the list comprehension.expression
: The operation or transformation applied to each item in the iterable.item
: The variable representing each element in the iterable.iterable
: The sequence (list, tuple, string, etc.) from which the elements are drawn.1numbers = [1, 2, 3, 4, 5]
2squared_numbers = [x**2 for x in numbers]
3print(squared_numbers) # Output: [1, 4, 9, 16, 25]
In this example, the list comprehension creates a new list squared_numbers
by squaring each element x
in the numbers
list.
List comprehensions can also include conditional statements to filter or transform elements based on specific conditions.
1numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2even_numbers = [x for x in numbers if x % 2 == 0]
3print(even_numbers) # Output: [2, 4, 6, 8, 10]
In this example, the list comprehension creates a new list even_numbers
by including only the elements x
from numbers
that are divisible by 2 (even numbers).
List comprehensions can be nested to create more complex expressions or work with multiple iterables.
1matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
2flattened = [num for row in matrix for num in row]
3print(flattened) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
In this example, the nested list comprehension[num for row in matrix for num in row]
flattens the nested matrix
list into a single list flattened
.
List comprehensions can also incorporate conditional expressions (ternary operators) to perform different operations based on conditions.
1numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
2result = ["even" if x % 2 == 0 else "odd" for x in numbers]
3print(result) # Output: ['odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even', 'odd', 'even']
In this example, the list comprehension ["even" if x % 2 == 0 else "odd" for x in numbers]
creates a new list result
by appending the string “even” if x
is even, and “odd” if x
is odd.
List comprehensions are powerful and expressive tools that can significantly improve the readability and conciseness of your code when working with lists and iterables in Python. They can help you write more Pythonic and efficient code, especially when dealing with complex data transformations or filtering operations.