Now that you’ve got the basics down and have successfully written your first Python script, it’s time to delve deeper. In this chapter, we’ll explore Python’s data structures—lists, tuples, dictionaries, and sets. Understanding these data structures is crucial as they form the backbone of most Python programs. Let’s get started!
Lists are one of the most commonly used data structures in Python. They are ordered, mutable, and can hold a variety of data types, including integers, strings, and even other lists.
You can create a list by placing comma-separated values within square brackets.
Example:
# Creating a list
fruits = ["apple", "banana", "cherry"]
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry (negative indexing starts from the end)
Since lists are mutable, you can modify their elements.
Example:
# Modifying an element
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
# Adding elements
fruits.append("date")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
# Removing elements
fruits.remove("blueberry")
print(fruits) # Output: ['apple', 'cherry', 'date']
Python provides several methods to work with lists.
Example:
# List of methods
numbers = [1, 2, 3, 4, 5]
# append()
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]
# insert()
numbers.insert(0, 0)
print(numbers) # Output: [0, 1, 2, 3, 4, 5, 6]
# pop()
numbers.pop()
print(numbers) # Output: [0, 1, 2, 3, 4, 5]
# sort()
numbers.sort(reverse=True)
print(numbers) # Output: [5, 4, 3, 2, 1, 0]
Tuples are similar to lists, but they are immutable, meaning once they are created, their elements cannot be changed. Tuples are useful for storing data that should not be modified.
You can create a tuple by placing comma-separated values within parentheses.
Example:
# Creating a tuple
coordinates = (10.0, 20.0)
# Accessing elements
print(coordinates[0]) # Output: 10.0
print(coordinates[1]) # Output: 20.0
Tuples are used for fixed data that should not change. They can also be used as keys in dictionaries because they are hashable.
Example:
# Using a tuple as a dictionary key
locations = {
(10.0, 20.0): "Location A",
(30.0, 40.0): "Location B"
}
print(locations[(10.0, 20.0)]) # Output: Location A
Dictionaries are unordered collections of key-value pairs. They are optimized for retrieving data when you know the key.
You can create a dictionary by placing key-value pairs within curly braces, separated by commas.
Example:
# Creating a dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Accessing elements
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 25
Dictionaries are mutable, so you can change their contents.
Example:
# Modifying a value
person["age"] = 26
print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
# Adding a new key-value pair
person["email"] = "alice@example.com"
print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York', 'email': 'alice@example.com'}
# Removing a key-value pair
del person["city"]
print(person) # Output: {'name': 'Alice', 'age': 26, 'email': 'alice@example.com'}
Python provides several methods to work with dictionaries.
Example:
# Dictionary of methods
inventory = {
"apples": 10,
"bananas": 5,
"oranges": 3
}
# keys()
print(inventory.keys()) # Output: dict_keys(['apples', 'bananas', 'oranges'])
# values()
print(inventory.values()) # Output: dict_values([10, 5, 3])
# items()
print(inventory.items()) # Output: dict_items([('apples', 10), ('bananas', 5), ('oranges', 3)])
# get()
print(inventory.get("apples")) # Output: 10
# update()
inventory.update({"apples": 15, "grapes": 8})
print(inventory) # Output: {'apples': 15, 'bananas': 5, 'oranges': 3, 'grapes': 8}
Sets are unordered collections of unique elements. They are useful for storing data when duplicates are not allowed.
You can create a set by placing comma-separated values within curly braces.
Example:
# Creating a set
fruits = {"apple", "banana", "cherry"}
# Accessing elements (though order is not guaranteed)
print(fruits) # Output: {'apple', 'cherry', 'banana'}
Sets are mutable, so you can add or remove elements.
Example:
# Adding elements
fruits.add("date")
print(fruits) # Output: {'apple', 'date', 'cherry', 'banana'}
# Removing elements
fruits.remove("banana")
print(fruits) # Output: {'apple', 'date', 'cherry'}
Sets support mathematical operations like union, intersection, and difference.
Example:
# Set operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
# Union
print(set1 | set2) # Output: {1, 2, 3, 4, 5}
# Intersection
print(set1 & set2) # Output: {3}
# Difference
print(set1 - set2) # Output: {1, 2}
You can combine different data structures to create complex data models. For example, a list of dictionaries or a dictionary of lists.
Example:
# List of dictionaries
students = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 22}
]
print(students[0]["name"]) # Output: Alice
# Dictionary of lists
grades = {
"math": [90, 80, 85],
"science": [95, 85, 80]
}
print(grades["math"][1]) # Output: 80
Question 1: Which of the following is a mutable data structure in Python? a) Tuple
b) String
c) List
d) Integer
Question 2: How do you create an empty dictionary in Python? a) []
b) {}
c) ()
d) None
Question 3: Which method is used to add an element to the end of a list? a) insert()
b) append()
c) add()
d) extend()
Question 4: What will be the output of len({'name': 'Alice', 'age': 25})
? a) 1
b) 2
c) 3
d) 0
Question 5: How do you access the first element of a list my_list
? a) my_list[0]
b) my_list[1]
c) my_list[-1]
d) my_list.first()
Question 6: Which of the following is an immutable data structure in Python? a) List
b) Set
c) Dictionary
d) Tuple
Question 7: How can you remove a key-value pair from a dictionary? a) del dict['key']
b) dict.pop('key')
c) dict.remove('key')
d) Both a and b
Question 8: What is the output of set([1, 2, 2, 3, 4, 4])
? a) {1, 2, 3, 4, 4}
b) [1, 2, 3, 4]
c) {1, 2, 3, 4}
d) (1, 2, 3, 4)
Question 9: How do you create a tuple with a single element? a) (1,)
b) (1)
c) [1]
d) tuple(1)
Question 10: Which method would you use to combine two lists list1
and list2
? a) list1.combine(list2)
b) list1.append(list2)
c) list1.add(list2)
d) list1.extend(list2)
Question 1: Which of the following is a mutable data structure in Python? c) List
Question 2: How do you create an empty dictionary in Python? b) {}
Question 3: Which method is used to add an element to the end of a list? b) append()
Question 4: What will be the output of len({'name': 'Alice', 'age': 25})
? b) 2
Question 5: How do you access the first element of a list my_list
? a) my_list[0]
Question 6: Which of the following is an immutable data structure in Python? d) Tuple
Question 7: How can you remove a key-value pair from a dictionary? d) Both a and b
Question 8: What is the output of set([1, 2, 2, 3, 4, 4])
? c) {1, 2, 3, 4}
Question 9: How do you create a tuple with a single element? a) (1,)
Question 10: Which method would you use to combine two lists list1
and list2
? d) list1.extend(list2)
Building blocks of Python programs: functions, modules, and packages.
Chapter 3
This website uses cookies.