FoPM4 Data Structures - Lists and Tuples
FoPM4 Data Structures - Lists and Tuples
Introduction to Sequences
In Python, a sequence is an ordered collection of items. Sequences allow you to store multiple
items in a single variable and access them by their position (index). Python has several built-in
sequence types, including lists, tuples, strings, and more. This discussion will focus on lists and
tuples.
Sequences are important because they allow you to handle collections of data in an organized and
efficient manner. They provide a way to store, access, and manipulate data in a structured format.
1. Creating Lists:
Lists are one of the most versatile and commonly used data structures in Python. A list is an
ordered collection of items, and it can contain items of different data types. Lists are created using
square brackets [], and items are separated by commas.
python
Copy
# Creating a list of integers
numbers = [1, 2, 3, 4, 5]
2. Indexing:
You can access individual elements of a list using their index. In Python, indexing starts at 0.
python
Copy
fruits = ["apple", "banana", "cherry", "date"]
# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[2]) # Output: cherry
Negative indexing is also supported, where -1 refers to the last element, -2 to the second last, and so on.
python
Copy
print(fruits[-1]) # Output: date
print(fruits[-3]) # Output: banana
3. Slicing:
Slicing allows you to extract a portion of the list. The syntax for slicing is list[start:stop:step],
where start is the index to begin, stop is the index to end (not inclusive), and step is the step size.
python
Copy
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4. Modifying Lists:
Lists are mutable, which means you can change their content after creation.
• Changing an element:
python
Copy
fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry" # Changing the second element
print(fruits) # Output: ['apple', 'blueberry', 'cherry']
• Adding elements:
python
Copy
fruits.append("date")
print(fruits) # Output: ['apple', 'blueberry', 'cherry', 'date']
o Using insert(): Inserts an element at a specified index.
python
Copy
fruits.insert(1, "grape")
print(fruits) # Output: ['apple', 'grape', 'blueberry', 'cherry', 'date']
• Removing elements:
python
Copy
fruits.remove("blueberry")
print(fruits) # Output: ['apple', 'grape', 'cherry', 'date']
o Using pop(): Removes and returns the element at the specified index.
python
Copy
popped_fruit = fruits.pop(2)
print(popped_fruit) # Output: cherry
print(fruits) # Output: ['apple', 'grape', 'date']
python
Copy
more_fruits = ["banana", "cherry"]
fruits.extend(more_fruits)
print(fruits) # Output: ['apple', 'date', 'banana', 'cherry']
• Sorting a list:
python
Copy
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
python
Copy
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
• Reversing a list:
python
Copy
numbers.reverse()
print(numbers) # Output: [9, 5, 4, 3, 2, 1, 1]
List Comprehensions
List comprehensions provide a concise way to create lists. They consist of an expression followed
by a for clause and possibly if clauses.
Syntax:
python
Copy
new_list = [expression for item in iterable if condition]
Examples:
python
Copy
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
python
Copy
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # Output: [0, 2, 4, 6, 8]
• Creating a list of uppercase letters from a string:
python
Copy
sentence = "Hello, World!"
uppercase_letters = [char.upper() for char in sentence if char.isalpha()]
print(uppercase_letters) # Output: ['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']
1. Creating Tuples:
Tuples are similar to lists, but they are immutable, meaning they cannot be changed after creation.
Tuples are created using parentheses (), and items are separated by commas.
python
Copy
# Creating a tuple of integers
numbers = (1, 2, 3, 4, 5)
You can access tuple elements using indexing and slicing, just like lists.
python
Copy
coordinates = (3, 4, 5)
print(coordinates[0]) # Output: 3
print(coordinates[1]) # Output: 4
print(coordinates[-1]) # Output: 5
3. Tuple Slicing:
python
Copy
letters = ('a', 'b', 'c', 'd', 'e')
4. Using Tuples:
Since tuples are immutable, they are often used for data that should not change. They can be used
to return multiple values from a function.
python
Copy
def get_coordinates():
return (3, 4, 5)
x, y, z = get_coordinates()
print(x, y, z) # Output: 3 4 5
• Using tuples as keys in dictionaries:
python
Copy
student_grades = {
("John", "Doe"): 90,
("Jane", "Smith"): 85,
("Alice", "Johnson"): 92
}
1. Length of a Sequence:
Use the len() function to get the number of items in a list or tuple.
python
Copy
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
coordinates = (3, 4, 5)
print(len(coordinates)) # Output: 3
2. Checking for Membership:
Use the in and not in operators to check if an item is present in a list or tuple.
python
Copy
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" not in fruits) # Output: True
Use the min() and max() functions to find the smallest and largest items in a sequence.
python
Copy
numbers = [5, 2, 9, 1, 5, 6]
print(min(numbers)) # Output: 1
print(max(numbers)) # Output: 9
python
Copy
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
• Repetition: Repeat a sequence using the * operator.
python
Copy
repeated_tuple = (1, 2) * 3
print(repeated_tuple) # Output: (1, 2, 1, 2, 1, 2)
python
Copy
fruits = ["apple", "banana", "cherry"]
o For lists:
python
Copy
numbers = [1, 2, 3, 4, 5]
print(numbers.index(3)) # Output: 2
o For tuples:
python
Copy
coordinates = (3, 4, 5)
print(coordinates.index(4)) # Output: 1
python
Copy
try:
print(fruits.index("grape"))
except ValueError:
print("Grape is not in the list.")
# Output: Grape is not in the list.
python
Copy
numbers = [1, 2, 3, 4, 5]
print(all(numbers)) # Output: True
python
Copy
mixed = [0, False, None, "", 5]
print(any(mixed)) # Output: True
1. Nested Lists:
python
Copy
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
• Accessing elements:
python
Copy
print(matrix[0][1]) # Output: 2
print(matrix[2][2]) # Output: 9
2. Nested Tuples:
python
Copy
point = ((3, 4), (5, 6))
• Accessing elements:
python
Copy
print(point[0]) # Output: (3, 4)
print(point[1][0]) # Output: 5
python
Copy
students = [
("Alice", 25),
("Bob", 22),
("Charlie", 24)
]
• Accessing elements:
python
Copy
print(students[1]) # Output: ('Bob', 22)
print(students[2][0]) # Output: Charlie
Type Casting
python
Copy
list_to_tuple = [1, 2, 3, 4]
tuple_version = tuple(list_to_tuple)
print(tuple_version) # Output: (1, 2, 3, 4)
• Converting a tuple to a list:
python
Copy
tuple_to_list = (1, 2, 3, 4)
list_version = list(tuple_to_list)
print(list_version) # Output: [1, 2, 3, 4]
python
Copy
string = "Hello"
list_from_string = list(string)
print(list_from_string) # Output: ['H', 'e', 'l', 'l', 'o']
python
Copy
range_to_list = list(range(5))
print(range_to_list) # Output: [0, 1, 2, 3, 4]
o Keys:
python
Copy
dict_to_list = list({"a": 1, "b": 2, "c": 3})
print(dict_to_list) # Output: ['a', 'b', 'c']
o Items:
python
Copy
items_tuple = tuple({"a": 1, "b": 2, "c": 3}.items())
print(items_tuple) # Output: (('a', 1), ('b', 2), ('c', 3))\
Summary
• Lists are mutable, ordered collections of items that can be modified after creation.
• Tuples are immutable, ordered collections of items that cannot be changed after creation.
• Both lists and tuples support indexing, slicing, and common operations
like len(), min(), max(), and in.
• Nested lists and tuples allow for the representation of complex data structures.
• Type casting allows conversion between lists, tuples, and other data types.
Exercises and Explanations: Manipulating Lists and Tuples, and Working with Nested Data
Structures
Code:
python
Copy
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print("Ascending order:", numbers)
numbers.sort(reverse=True)
print("Descending order:", numbers)
Explanation:
Task: Find the index of an item in a list and check for membership.
Code:
python
Copy
fruits = ["banana", "apple", "cherry"]
try:
print("Index of cherry:", fruits.index("cherry"))
except ValueError:
print("Cherry not found")
if "date" in fruits:
print("Date is in the list")
else:
print("Date is not in the list")
Explanation:
• The index() method returns the index of the first occurrence of the item.
Code:
python
Copy
original_tuple = (3, 1, 4, 1, 5, 9, 2)
sorted_tuple = tuple(sorted(original_tuple))
print("Sorted tuple:", sorted_tuple)
Explanation:
• Tuples are immutable, so we convert them to a list, sort them, and convert back to a tuple.
Code:
python
Copy
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Element at row 1, column 1:", matrix[1][1])
Explanation:
• matrix[1][1] accesses the element at the second row and second column.
Code:
python
Copy
students = [("Alice", 25), ("Bob", 22), ("Charlie", 24)]
sorted_students = sorted(students, key=lambda x: x[1])
print("Sorted by age:", sorted_students)
Explanation:
• The sorted() function with a key parameter sorts the list based on the specified element of
the tuple.
Code:
python
Copy
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [element for sublist in matrix for element in sublist]
print("Flattened list:", flattened)
Explanation:
• A nested list comprehension iterates through each sublist and then through each element
in the sublist.
Task: Demonstrate the difference between shallow copy and deep copy.
Code:
python
Copy
import copy
original = [[1, 2], [3, 4]]
shallow_copy = original.copy()
deep_copy = copy.deepcopy(original)
original[0][0] = 0
print("Original after change:", original)
print("Shallow copy after change:", shallow_copy)
print("Deep copy after change:", deep_copy)
Explanation:
• A shallow copy copies the list but not the nested lists.
Code:
python
Copy
points = [(1, 2), (3, 4), (5, 6)]
x_coords = [point[0] for point in points]
print("X-coordinates:", x_coords)
Explanation:
• A list comprehension iterates through each tuple and selects the first element.
python
Copy
items = [("apple", 1), ("banana", 2)]
items[0] = ("orange", 1)
print("Modified list:", items)
Explanation:
• Since tuples are immutable, we replace the entire tuple at a specific index.
Code:
python
Copy
fruits = ["apple", "banana", "cherry"]
search_item = "date"
if search_item in fruits:
print(f"{search_item} found at index {fruits.index(search_item)}")
else:
print(f"{search_item} not found in the list")
Explanation:
• Using in keyword and index() method together ensures safe searching without exceptions.
These exercises cover fundamental operations on lists and tuples, including sorting, searching, and
working with nested data structures. Understanding these concepts is crucial for effective data
manipulation in Python.
1. What is the difference between a list and a tuple in Python?
➢ Lists are mutable and use square brackets [], while tuples are immutable and use
parentheses ().
➢ You create a list by assigning values in square brackets, e.g., my_list = [1, 2, 3].
➢ You access the third element with my_list[2] since indexing starts at 0.
➢ Tuples are used when data shouldn't change, providing immutability and safety.
➢ The len() function returns the number of elements in the list or tuple.