Lecture 5 β Iterable Objects and Containers#
π― Learning Objectives
By the end of this lecture, you will be able to:
- β
Create and manipulate
list,tuple,dict, andset - β Use indexing, slicing, and iteration on containers
- β Understand mutability vs. immutability
- β
Apply common methods:
append,pop,update,keys - β Choose the right container for each task
π Practice Exercises
- List operations: Create a list of 5 cities. Append a 6th city, insert one at position 2, remove the last one, and sort the list alphabetically.
- Dictionary builder: Create a dictionary mapping 5 country names to their capitals. Add a new country, update one capital, and print all key-value pairs.
- Set operations: Create two sets: students who passed math and students who passed science. Find students who passed both, either, and only one subject.
- Nested containers: Create a list of dictionaries representing 3 students, each with keys
"name","age", and"grades"(a list of numbers). Print the average grade for each student. - Challenge: Given
text = "the quick brown fox jumps over the lazy dog", use a dictionary to count how many times each word appears.
# Exercise 1: List operations
cities = []
# Your code here
# Exercise 2: Dictionary builder
countries = {}
# Your code here
# Exercise 3: Set operations
passed_math = {"Alice", "Bob", "Charlie", "Diana"}
passed_science = {"Bob", "Diana", "Eve", "Frank"}
# Your code here
# Exercise 4: Nested containers
students = []
# Your code here
# Exercise 5 (Challenge): Word counter
text = "the quick brown fox jumps over the lazy dog"
# Your code here
Click to show solution
# Exercise 1: List operations
cities = ["Paris", "London", "Tokyo", "Berlin", "Sydney"]
cities.append("Cairo")
cities.insert(2, "Rome")
cities.pop()
cities.sort()
print(cities)
# Exercise 2: Dictionary builder
countries = {
"France": "Paris",
"Japan": "Tokyo",
"Germany": "Berlin",
"Brazil": "Brasilia",
"Australia": "Canberra",
}
countries["Canada"] = "Ottawa"
countries["Germany"] = "Berlin (confirmed)"
for country, capital in countries.items():
print(f"{country}: {capital}")
# Exercise 3: Set operations
passed_math = {"Alice", "Bob", "Charlie", "Diana"}
passed_science = {"Bob", "Diana", "Eve", "Frank"}
both = passed_math & passed_science
either = passed_math | passed_science
only_one = passed_math ^ passed_science
print(f"Both: {both}")
print(f"Either: {either}")
print(f"Only one: {only_one}")
# Exercise 4: Nested containers
students = [
{"name": "Alice", "age": 20, "grades": [85, 92, 78]},
{"name": "Bob", "age": 22, "grades": [70, 65, 80]},
{"name": "Charlie", "age": 21, "grades": [95, 88, 92]},
]
for s in students:
avg = sum(s["grades"]) / len(s["grades"])
print(f"{s['name']}: average grade = {avg:.1f}")
# Exercise 5 (Challenge): Word counter
text = "the quick brown fox jumps over the lazy dog"
word_counts = {}
for word in text.split():
word_counts[word] = word_counts.get(word, 0) + 1
print(word_counts)
π Table of Contents
π Building on What You Know
So far, you've worked with individual values: a number, a string, a boolean. But real programs need to manage collections of data β a list of temperatures, a mapping of student names to grades, a set of unique IDs. Python provides four powerful container types for exactly this purpose.
π Real-World Scenario
You are building an application to manage student records at a university. You need a list of enrolled students (ordered, can change), a tuple for each student's immutable ID and birth date, a dictionary mapping student IDs to their grades for fast lookup, and a set to track which courses have been taken (no duplicates).
Each container type exists because it solves a different kind of problem. By the end of this lecture, you'll know which container to reach for in any situation.
π§Ύ Summary
This lecture aims to present iterable objects and containers, focusing on lists, tuples, dictionaries, and sets. We will review some of the most commonly encountered operations with these data structures, particularly in data organization and retrieval tasks. Additionally, we will explore how to use lists, tuples, dictionaries, and sets to efficiently store and manage collections of data.
π Key Concepts
- π Iterable Objects: Understanding sequences and containers in Python
- ποΈ Data Structures: Lists, tuples, dictionaries, and sets
- π Common Operations: Data organization and retrieval techniques
- πΎ Efficient Storage: Managing collections of data effectively
π Resources
- π GitHub Repository: PyPro-SCiDaS β The Shell
- π‘ Feel free to explore, fork, and practice before the session!
ποΈ Python Data Structures Overview
As mentioned in previous sections, a Python program always operates based on the manipulation of objects. The instructions are always executed on objects. Variables represent a particular type of Python object. In general, instructions in a Python program are defined from a collection of objects that come in various forms of value sequences.
π List Object
A list object is a sequence of values (numerical and/or characters) that are indexed and specified within square brackets, separated by commas.
y = ["Olivier", "ENGEL", "Strasbourg"] # List consisting only of characters
z = [1, "Olivier", 5, 8, "ENGEL", 10, 4, 50, "Strasbourg"] # Mixed list
A list object can be generated manually or automatically using the list() function.
print(x) # returns [1, 2, 3, 4, 5, 6, 7, 8, 9]
π¦ Tuple Object
A tuple object is a sequence of values (numerical and/or characters) that are indexed and specified within parentheses, separated by commas.
y = ("Olivier", "ENGEL", "Strasbourg") # Tuple consisting only of characters
z = (1, "Olivier", 5, 8, "ENGEL", 10, 4, 50, "Strasbourg") # Mixed tuple
A tuple object can be generated manually or automatically using the tuple() function.
print(x) # returns (1, 2, 3, 4, 5, 6, 7, 8, 9)
π― Set Object
A set object is a sequence of values (numerical and/or characters) that are non-duplicated and non-indexed, and specified within curly braces, separated by commas.
y = {"Olivier", "ENGEL", "Strasbourg"} # Set consisting only of characters
z = {1, "Olivier", 5, 8, "ENGEL", 10, 4, 50, "Strasbourg"} # Mixed set
A set object can be generated manually or automatically using the set() function.
V = set(v)
print(V) # returns {2, 'orange', 4, 'meat'}
π Dictionary Object
A dictionary object is a sequence of values (numerical and/or characters) that are indexed by keys and specified within curly braces, separated by commas. Each key corresponds to one or more values.
y = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]} # Key with list values
A dictionary object can be generated manually or automatically using the dict() function.
π¦ Container Properties
The four objects we have just mentioned are also what we call containers simply because they can contain something. Thus, strings, lists, tuples, and dictionaries are the basic iterable objects in Python. Lists and dictionaries are mutable β their elements can be changed on the fly β while strings and tuples are immutable.
π 0. Lists
π 0.0. Definition of a list object
A list object can be declared and defined manually or by using the list() function. There are two categories of lists: one-dimensional lists (or simple lists) and multi-dimensional lists.
- A simple list is a list whose elements consist of unique values separated by commas.
voltage = [-2.0, -1.0, 0.0, 1.0, 2.0]
courant = [-1.0, -0.5, 0.0, 0.5, 1.0]
print(voltage)
print("============================= \n")
print(courant)
[-2.0, -1.0, 0.0, 1.0, 2.0]
=============================
[-1.0, -0.5, 0.0, 0.5, 1.0]
type(voltage) # Returns the type of the variable 'courant'
list
# Check the variable type
type(courant)
list
# Get help documentation
help(voltage.sort())
Help on NoneType object:
class NoneType(object)
| The type of the None singleton.
|
| Methods defined here:
|
| __bool__(self, /)
| True if self else False
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __lt__(self, value, /)
| Return self<value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
Moreover, in some situations, you may first create an empty list which will later be filled with values using the append() function. To create an empty list, you can use:
x = list() or x = [].
- Unlike a simple list, a multi-dimensional list is a list where the individual elements consist of multiple values. In general, a multi-dimensional list is presented as a list of lists.
x = [[1,2,3],[2,3,4],[3,4,5]] # liste Γ deux dimensions (liste de listes)
y = [[[1,2],[2,3]],[[4,5],[5,6]]] # liste Γ trois dimensions (liste de listes de listes)
x,y
([[1, 2, 3], [2, 3, 4], [3, 4, 5]], [[[1, 2], [2, 3]], [[4, 5], [5, 6]]])
Since a list is a sequence of indexed values, you can access each value or groups of values by specifying their index:
x = list(['Monday', 'Tuesday', 'Wednesday', 1800, 20.357, 'Thursday', 'Friday']) # Definition of a list
print(x) # Displays all the elements of the list x
['Monday', 'Tuesday', 'Wednesday', 1800, 20.357, 'Thursday', 'Friday']
print(x[0]) # Returns the first element of x: 'Monday' (Note: indexing starts at 0)
print("================================================")
print('\t')
print(x[3]) # Returns the element at index 3 (fourth element of x): 1800
print("================================================")
print('\t')
print(x[1:3]) # Returns all elements between index 1 and index 3 (Note: element at index 3 is excluded)
print("================================================")
print('\t')
print(x[1:6:2]) # Returns all elements between index 1 and index 6 with a step of 2 elements each time ['Tuesday', 1800, 'Thursday'] (element at index 6 is excluded).
print("================================================")
print('\t')
print(x[2:]) # Returns all elements starting from index 2 (inclusive).
print("================================================")
print('\t')
print(x[:3]) # Returns all elements up to but not including index 3
print("================================================")
print('\t')
print(x[-1]) # Negative indexing, returns the last element of the list (equivalent to x[6])
print("================================================")
print('\t')
print(x[-2]) # Negative indexing, returns the second to last element of the list (equivalent to x[5])
print("================================================")
print('\t')
print(x[::2]) # Iterates through all elements between index 0 and the last index, returning every second element ['Monday', 'Wednesday', 20.357, 'Friday'].
print("================================================")
print('\t')
print(x[::-1]) # Returns a list containing all elements of x, rearranged from the last element to the first. This is a reverse of x. Returns ['Friday', 'Thursday', 20.357, 1800, 'Wednesday', 'Tuesday', 'Monday'].
# The same result can be obtained by using x.reverse()
x_rev = x.reverse()
x_rev
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[5], line 1
----> 1 print(x[0]) # Returns the first element of x: 'Monday' (Note: indexing starts at 0)
2 print("================================================")
3 print('\t')
NameError: name 'x' is not defined
With a multi-dimensional list, indexing is done at multiple levels. For example
x = [[1, 2, 3], [2, 3, 4], [3, 4, 5]]
print(x)
print("================================================")
print('\t')
print(x[0]) # Returns the first sublist [1, 2, 3]
print("================================================")
print('\t')
print(x[0][0]) # Returns the first element of the first sublist, which is 1
print("================================================")
print('\t')
print(x[2]) # Returns the third sublist [3, 4, 5]
print("================================================")
print('\t')
print(x[2][1]) # Returns the element at index 1 of the third sublist, which is 4
print("================================================")
print('\t')
print(x[1:]) # Returns all sublists starting from index 1: [[2, 3, 4], [3, 4, 5]]
print("================================================")
print('\t')
print(x[1:][0]) # Returns the first sublist from the sliced list: [2, 3, 4]
print("================================================")
print('\t')
print(x[-1]) # Returns the last sublist [3, 4, 5]
print("================================================")
print('\t')
print(x[1][:2]) # Returns the first two elements of the second sublist: [2, 3]
print("================================================")
print('\t')
print(x[1][1:]) # Returns elements from index 1 to the end of the second sublist: [3, 4]
[[1, 2, 3], [2, 3, 4], [3, 4, 5]]
================================================
[1, 2, 3]
================================================
1
================================================
[3, 4, 5]
================================================
4
================================================
[[2, 3, 4], [3, 4, 5]]
================================================
[2, 3, 4]
================================================
[3, 4, 5]
================================================
[2, 3]
================================================
[3, 4]
π’ 0.1. The range() Function
Value sequences are variables that are frequently encountered in Python programs. They represent a set of successive and ordered values that can be extracted like a list. Value sequences are generated using the range() function.
The function has the following syntax:
start(optional): The value of the first number in the sequence. If omitted, the sequence starts from 0.stop: The end of the sequence. This value is not included in the sequence.step(optional): The difference between each pair of consecutive values in the sequence. If omitted, the default step is 1.
Example:
x = range(10) # Creates a sequence of integer values from 0 to 9
print(x)
print("================================================")
print('\t')
x = range(2, 10) # Creates a sequence of integer values from 2 to 9
print(x)
print("================================================")
print('\t')
x = range(1, 10, 2) # Creates a sequence of integer values from 1 to 9 with a step of 2. It returns 1, 3, 5, 7, and 9
print(x)
range(0, 10)
================================================
range(2, 10)
================================================
range(1, 10, 2)
To display the generated values, you can use the list() function, as shown below:
x = range(10)
print(list(x)) # Returns a list: values in square brackets [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
π§ 0.2. Operations on Lists
Once a list is defined, several operations can be performed to modify its structure or its elements.
- To find the number of elements in a list, we use the
len()function. Example: consider the listxdefined as follows:
To find the length of x (the number of elements in x), we do:
x = ['Monday', 'Tuesday', 'Wednesday', 1800, 20.357, 'Thursday', 'Friday']
print(len(x)) # returns 7
7
- We can concatenate two lists to form a single list using the
+operator, which allows for list concatenation:
y = ['monkey', 'mouse']
z = x + y
print(z) # returns ['giraffe', 'tiger', 'monkey', 'mouse']
x = ['giraffe', 'tiger']
y = ['monkey', 'mouse']
z = x + y
print(z) # returns ['giraffe', 'tiger', 'monkey', 'mouse']
['giraffe', 'tiger', 'monkey', 'mouse']
- We can repeat the elements of a list using the multiplication operator
*:
y = x * 3
print(y) # returns ['giraffe', 24, 18, 'tiger', 2400, 150, 'giraffe', 24, 18, 'tiger', 2400, 150, 'giraffe', 24, 18, 'tiger', 2400, 150]
x = ['giraffe', 24, 18, 'tiger', 2400, 150]
y = x * 3
print(y) # returns ['giraffe', 24, 18, 'tiger', 2400, 150, 'giraffe', 24, 18,
# 'tiger', 2400, 150, 'giraffe', 24, 18, 'tiger', 2400, 150]
['giraffe', 24, 18, 'tiger', 2400, 150, 'giraffe', 24, 18, 'tiger', 2400, 150, 'giraffe', 24, 18, 'tiger', 2400, 150]
- It is possible to modify a particular element in a list by using its index:
x[3] = x[3] + 100
print(x) # returns ['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday']
x[6] = x[6] + ' Saint' # Note the space in ' Saint', otherwise you'll get 'FridaySaint'.
print(x) # returns ['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday Saint']
x = ['Monday', 'Tuesday', 'Wednesday', 1800, 20.357, 'Thursday', 'Friday']
x[3] = x[3] + 100
print(x) # returns ['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday']
print("==================================================================\n")
x[6] = x[6] + ' Saint' # Note the space in ' Saint', otherwise you'll get 'FridaySaint'.
print(x) # returns ['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday Saint']
['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday']
==================================================================
['Monday', 'Tuesday', 'Wednesday', 1900, 20.357, 'Thursday', 'Friday Saint']
- New elements can be added in addition to the initial elements. For this, we use the
append()function:
x.append('Saturday')
x.append('Sunday')
print(x)
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.append('Saturday')
x.append('Sunday')
print(x)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
As we can see, the append() function can only add one element to a list at a time. Therefore, we can use the extend() function when we want to add multiple elements at once. Example:
x.extend(['Saturday', 'Sunday'])
print(x)
x = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
x.extend(['Saturday', 'Sunday'])
print(x)
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
π Further Study: Explore the following methods and how they operate on lists:
insert(), remove(), index(), count().
π‘ Note: Given that their usage is quite uncommon, we will not cover tuple and set objects in this course. The brief presentation given above is relatively sufficient, and readers who explicitly need more information can consult the extensive documentation available online.
However, we can mention that a set is an unordered iterable collection of distinct hashable elements and that classic mathematical operations on sets can be performed in Python. For example:
print("X =", X) # X = {'a', 'c', 'b', 'd'}
print("Y =", Y) # Y = {'s', 'b', 'd'} : only one element 's'
print('c' in X) # True
print('a' in Y) # False
print(X - Y) # {'a', 'c'}
print(Y - X) # {'s'}
print(X | Y) # {'a', 'c', 'b', 'd', 's'}
print(X & Y) # {'b', 'd'}
X, Y = set('abcd'), set('sbds')
print("X =", X) # X = {'a', 'c', 'b', 'd'}
print("=========================================\n")
print("Y =", Y) # Y = {'s', 'b', 'd'} : only one element 's'
print("=========================================\n")
print('c' in X) # True
print("=========================================\n")
print('a' in Y) # False
print("=========================================\n")
print(X - Y) # {'a', 'c'}
print("=========================================\n")
print(Y - X) # {'s'}
print("=========================================\n")
print(X | Y) # {'a', 'c', 'b', 'd', 's'}
print("=========================================\n")
print(X & Y) # {'b', 'd'}
X = {'a', 'd', 'b', 'c'}
=========================================
Y = {'s', 'd', 'b'}
=========================================
True
=========================================
False
=========================================
{'a', 'c'}
=========================================
{'s'}
=========================================
{'d', 'b', 'c', 's', 'a'}
=========================================
{'d', 'b'}
π 1. Dictionaries
π 1.0. About dictionaries
In Pythonic design, a dictionary (also called a map) is a versatile collection of objects that adheres to the key-value principle. Unlike lists, where elements are accessed by their position or index, dictionaries use unique keys to identify and retrieve values. These keys are typically strings but can also be other immutable types, such as numbers or tuples. This key-value structure allows for efficient lookups, additions, and deletions, making dictionaries a powerful tool for organizing and managing data in a more intuitive and flexible way compared to lists.
x = {'name': 'Jean', 'age': 25, 'weight': 70, 'height': 1.75}
y = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
z = {'Jean': (25, 70, 1.75), 'Paul': (30, 65, 1.80), 'Pierre': (35, 75, 1.65)}
k = {'name': 'Jean', 'biometrics': [25, 70, 1.75], 'score': (12, 17, 15), 'rank': 25}
The four variables above represent four typical ways to define a dictionary. Variable x is a dictionary where the keys are name, age, weight, and height. The corresponding values are Jean, 25, 70, and 1.75. In the definition of x, it is noted that each key corresponds to a unique value. However, it is very common to associate multiple values with a single key. This is the case with dictionary y.
π§ 1.1. Operations on dictionaries
- To access the elements of a dictionary, you use the keys. The method
keys()returns the list of keys in the dictionary, and the methodvalues()returns the values.
print(X.keys()) # returns ['name', 'age', 'weight', 'height']
print(X.values()) # returns ['Jean', 25, 70, 1.75]
print(X['name']) # returns 'Jean'
x = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
print(x['Jean']) # returns [25, 70, 1.75]
print(x['Jean'][0]) # returns 25
print(x['Jean'][0:2]) # returns [25, 70]
X = {'name': 'Jean', 'age': 25, 'weight': 70, 'height': 1.75}
print("=========================================\n")
print(X.keys()) # returns ['name', 'age', 'weight', 'height']
print("=========================================\n")
print(X.values()) # returns ['Jean', 25, 70, 1.75]
print("=========================================\n")
print(X['name']) # returns 'Jean'
print("=========================================\n")
x = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
print("=========================================\n")
print(x['Jean']) # returns [25, 70, 1.75]
print("=========================================\n")
print(x['Jean'][0]) # returns 25
print("=========================================\n")
print(x['Jean'][0:2]) # returns [25, 70]
=========================================
dict_keys(['name', 'age', 'weight', 'height'])
=========================================
dict_values(['Jean', 25, 70, 1.75])
=========================================
Jean
=========================================
=========================================
[25, 70, 1.75]
=========================================
25
=========================================
[25, 70]
- Adding or modifying keys or values: You can modify a dictionary by either changing existing keys and values or by adding new ones. You can also remove values as well as keys.
x['name'] = 'Jean' # Adds the key-value pair 'name' and 'Jean' to the initial dictionary x
x['biometrics'] = [25, 70, 1.75] # Adds the key-value pair 'biometrics' and [25, 70, 1.75] to dictionary x
x['biometrics'] = [30, 70, 1.80] # Modifies the values of the 'biometrics' key by redefining it
x['biometrics'][0] = 2 # Modifies the element at index 0 in the list of values corresponding to the 'biometrics' key (previously defined)
Y = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
del Y['Jean'] # Deletes the key 'Jean' and all its corresponding values
del Y['Paul'][0] # Deletes the element at index 0 in the value sequence corresponding to the key 'Paul'. For a key with a single value, use del x['keyName'] where 'keyName' is the name of the key with the single value.
x = {} # Creates an empty dictionary. You could also use x = dict()
print(x)
print("=========================================\n")
x['name'] = 'Jean' # Adds the key-value pair 'name' and 'Jean' to the initial dictionary x
print(x)
print("=========================================\n")
x['biometrics'] = [25, 70, 1.75] # Adds the key-value pair 'biometrics' and [25, 70, 1.75] to dictionary x
print(x)
print("=========================================\n")
x['biometrics'] = [30, 70, 1.80] # Modifies the values of the 'biometrics' key by redefining it
print(x)
print("=========================================\n")
x['biometrics'][0] = 2 # Modifies the element at index 0 in the list of values corresponding to the 'biometrics' key (previously defined)
print(x)
print("=========================================\n")
Y = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
print(Y)
print("=========================================\n")
del Y['Jean'] # Deletes the key 'Jean' and all its corresponding values
del Y['Paul'][0] # Deletes the element at index 0 in the value sequence corresponding to the key 'Paul'. For a key with a single value, use del x['keyName'] where 'keyName' is the name of the key with the single value.
print(Y)
{}
=========================================
{'name': 'Jean'}
=========================================
{'name': 'Jean', 'biometrics': [25, 70, 1.75]}
=========================================
{'name': 'Jean', 'biometrics': [30, 70, 1.8]}
=========================================
{'name': 'Jean', 'biometrics': [2, 70, 1.8]}
=========================================
{'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.8], 'Pierre': [35, 75, 1.65]}
=========================================
{'Paul': [65, 1.8], 'Pierre': [35, 75, 1.65]}
- To rename a key in a dictionary, you use the
pop()function as defined in the following example:
x['John'] = x.pop('Jean') # Renames the key 'Jean' to 'John'
print(x)
x = {'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.80], 'Pierre': [35, 75, 1.65]}
print(x)
x['John'] = x.pop('Jean') # Renames the key 'Jean' to 'John'
print(x)
{'Jean': [25, 70, 1.75], 'Paul': [30, 65, 1.8], 'Pierre': [35, 75, 1.65]}
{'Paul': [30, 65, 1.8], 'Pierre': [35, 75, 1.65], 'John': [25, 70, 1.75]}
π― Key Takeaways
- Lists are ordered, mutable sequences β the most versatile Python container.
- Tuples are ordered but immutable β use them for fixed collections and dictionary keys.
- Dictionaries store key-value pairs with fast lookup:
d["key"]. - Sets store unique elements and support mathematical set operations (union, intersection).
- Choose the right container: lists for ordered data, dicts for lookups, sets for uniqueness, tuples for immutability.
β
β