u03-slides-data-structures-flashcards
What are the main types of data structures in Python?
Sequence types (list, tuple, string, range), unordered collections (set), and mapping types (dictionary)
How is a list created in Python?
Using square brackets containing comma-separated values (e.g.
What is special about Python lists?
They are mutable, can contain mixed data types, can be nested, and preserve order
At what index do Python sequences start?
0
What is the difference between lists and tuples?
Tuples are immutable (cannot be changed after creation), while lists are mutable
How are tuples created in Python?
Using comma-separated values, optionally enclosed in parentheses (e.g., my_tuple = 42, “text”, 3.14)
What is a set in Python?
An unordered collection of unique elements, created using set() or curly braces
Set:
A collection of unordered, mutable, and unique elements.
Defined using curly braces {} or the set() constructor.
Example:
my_set = {1, 2, 3}
my_set = set([1, 2, 3]) # Alternative
What are common set operations in Python?
Union (|), intersection (&), difference (-)
What is a dictionary in Python?
A mutable and ordered collection of key-value pairs
How are dictionaries created in Python?
Output: {‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}
1. Using Curly Braces
my_dict = { "key1": "value1", "key2": "value2", "key3": "value3" } print(my_dict)
2. Using the dict() Constructor
my_dict = dict(key1="value1", key2="value2", key3="value3") print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
3. From a List of Tuples
- Convert a list of key-value tuples into a dictionary:
my_dict = dict([("key1", "value1"), ("key2", "value2"), ("key3", "value3")]) print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
4. Using Dictionary Comprehension
- Create a dictionary dynamically:
my_dict = {x: x**2 for x in range(1, 4)} print(my_dict) # Output: {1: 1, 2: 4, 3: 9}
5. From Two Separate Iterables
- Use the zip() function to pair keys and values:
keys = ["key1", "key2", "key3"] values = ["value1", "value2", "value3"] my_dict = dict(zip(keys, values)) print(my_dict) # Output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
6. Empty Dictionary
- Create an empty dictionary:
my_dict = {} print(my_dict) # Output: {}
What can be used as dictionary keys?
Any hashable object
What can be used as dictionary values?
Any object
What is a list comprehension?
Explain the key concepts!
Output: [0, 1, 4, 9, 16]
A compact way to create a list by looping over an iterable, with optional filtering and transformations
Key Concepts:
- Basic Syntax:
[expression for item in iterable]
- With Filter:
[expression for item in iterable if condition]
- Transform and Filter Together:
[transform for item in iterable if condition]
Create a list of squares using list comprehension (base values zero to five)
Simple List Comprehension
A list comprehension creates a new list by iterating over an existing sequence.
Example 1: Create a list of squares
squares = [x**2 for x in range(5)] print(squares)
Filter even numbers using list comprehension for the integer numbers from zero to ten
Output: [0, 2, 4, 6, 8]
List Comprehension with Filters
You can add a condition to include only certain elements in the resulting list.
Example 2: Filter even numbers
even_numbers = [x for x in range(10) if x % 2 == 0] print(even_numbers)
Using list comprehension create a list containing the double value of each element in a range from 0 to 5.
Output: [0, 2, 4, 6, 8]
List Comprehension with Transformers
You can apply a transformation to each element in the list.
Example 3: Double the value of each element
doubled_numbers = [x * 2 for x in range(5)] print(doubled_numbers)
Create a list of the squares of the odd numbers from 0 to 10 using list comprehension.
Output: [1, 9, 25, 49, 81]
Combining Filters and Transformers
You can filter elements and then transform them in the same comprehension.
Example 4: Squares of odd numbers
odd_squares = [x**2 for x in range(10) if x % 2 != 0] print(odd_squares)
What does this output
Example 5: Create a multiplication table
multiplication_table = [[i * j for j in range(1, 4)] for i in range(1, 4)] print(multiplication_table)
Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
[[1, 2, 3], [2, 4, 6], [3, 6, 9]]
You can use a list comprehension inside a
Nested List Comprehension
What is the syntax for slicing in Python?
sequence[start:end:step]
where start is inclusive and end is exclusive
What happens when using negative numbers in slicing?
They count from the end (-1 for last element, -2 for second-last, etc.)
What is unpacking in Python?
Tuple unpacking
Assigning values from a sequence directly to multiple variables (e.g., a, b, c = [1, 2, 3])
How to unpack the following tuple or list into x, y coordinates?
point = (3, 4)
Unpacking a Tuple or List
~~~
point = (3, 4)
x, y = point
print(x) # Output: 3
print(y) # Output: 4
List unpacking
colors = [“red”, “green”, “blue”]
a, b, c = colors
print(a, b, c) # Output: red green blue
~~~
What will the following code do and what do you call the operation?
numbers = [1, 2, 3, 4, 5] a, b, *rest = numbers start, *middle, end = numbers
Using * for Variable-Length Unpacking
~~~
numbers = [1, 2, 3, 4, 5]
First two into separate variables, the rest into another
a, b, *rest = numbers
print(a, b, rest) # Output: 1 2 [3, 4, 5]
Collect the middle values
start, *middle, end = numbers
print(start, middle, end) # Output: 1 [2, 3, 4] 5
~~~
What does this code do and what du you call the operaton?
pairs = [(1, 'a'), (2, 'b'), (3, 'c')] for number, letter in pairs: print(f"Number: {number}, Letter: {letter}")
Unpacking in a Loop
~~~
pairs = [(1, ‘a’), (2, ‘b’), (3, ‘c’)]
for number, letter in pairs:
print(f”Number: {number}, Letter: {letter}”)
# Output:
# Number: 1, Letter: a
# Number: 2, Letter: b
# Number: 3, Letter: c
~~~
How to unpact first the keys only and second the keys and values from the dictionary:
my_dict = {"name": "Alice", "age": 30}
Unpack keys
Unpacking Dictionaries
~~~
my_dict = {“name”: “Alice”, “age”: 30}
for key in my_dict:
print(key)
# Output: name age
for key, value in my_dict.items():
print(f”{key}: {value}”)
# Output:
# name: Alice
# age: 30
~~~
What does immutable mean in Python?
Objects that cannot be changed after creation (e.g.
What does mutable mean in Python?
Objects that can be changed after creation (e.g.
Which of the following data type are immutable:
Custom Object, Strings, Tuples, Frozen Sets, Dictionaries, Sets, Booleans, Lists, Bytes, Byte Array
Examples of Immutable Data Types:
1. Numbers:
* Integers (int): 42
* Floating-point numbers (float): 3.14
* Complex numbers (complex): 2 + 3j
2. Strings (str): “hello”
3. Tuples (tuple): (1, 2, 3)
4. Frozen Sets (frozenset): frozenset([1, 2, 3])
5. Booleans (bool): True, False
6. Bytes (bytes): b”immutable”
Which of the following data type are mutable:
Custom Object, Strings, Tuples, Frozen Sets, Dictionaries, Sets, Booleans, Lists, Bytes, Byte Array
Mutable Data Types
These can be modified after creation. Operations that modify their contents affect the same object in memory.
Examples of Mutable Data Types:
1. Lists (list): [1, 2, 3]
2. Dictionaries (dict): {“key”: “value”}
3. Sets (set): {1, 2, 3}
4. Byte Arrays (bytearray): bytearray(b”mutable”)
5. Custom Objects: If the class allows modifications to its attributes.
What happens when you assign a mutable object to a new variable?
Both variables reference the same object, changes to one affect the other (alias effect)
How can you avoid side effects with mutable objects?
By making a copy of the object before modifying it
What are some examples of immutable objects in Python?
Integers, tuples, strings
What are some examples of mutable objects in Python?
Lists, dictionaries, sets
Why is dictionary order significant in Python?
Since Python 3.7 dictionaries preserve insertion order
What happens if you add a duplicate key to a dictionary?
It overwrites the previous value for that key
What happens when you slice with a negative step?
It reverses the order (e.g., my_list[::-1] reverses the entire sequence)