[go: up one dir, main page]

0% found this document useful (0 votes)
16 views26 pages

FoPM4 Data Structures - Lists and Tuples

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views26 pages

FoPM4 Data Structures - Lists and Tuples

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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.

Lists: Creating, Indexing, Slicing, and Modifying

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]

# Creating a list with mixed data types


mixed_list = [1, "Hello", 3.14, True]

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]

# Slicing from index 2 to 5


print(numbers[2:5]) # Output: [2, 3, 4]
# Slicing from the beginning to index 5
print(numbers[:5]) # Output: [0, 1, 2, 3, 4]

# Slicing from index 5 to the end


print(numbers[5:]) # Output: [5, 6, 7, 8, 9]

# Slicing with a step of 2


print(numbers[::2]) # Output: [0, 2, 4, 6, 8]

# Reversing the list


print(numbers[::-1]) # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

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:

o Using append(): Adds an element to the end of the list.

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:

o Using remove(): Removes the first occurrence of the specified value.

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']

o Using del: Deletes an item at a specified index.


python
Copy
del fruits[1]
print(fruits) # Output: ['apple', 'date']

• Adding multiple elements:

o Using extend(): Adds elements from another list to the end.

python
Copy
more_fruits = ["banana", "cherry"]
fruits.extend(more_fruits)
print(fruits) # Output: ['apple', 'date', 'banana', 'cherry']

• Sorting a list:

o Using sort(): Sorts the list in place.

python
Copy
numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers) # Output: [1, 1, 2, 3, 4, 5, 9]

o Using sorted(): Returns a new sorted list.

python
Copy
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [1, 1, 2, 3, 4, 5, 9]
• Reversing a list:

o Using reverse(): Reverses the list in place.

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:

• Creating a list of squares:

python
Copy
squares = [x**2 for x in range(10)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

• Creating a list of even numbers:

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']

Tuples: Creating and Using Tuples

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)

# Creating a tuple with mixed data types


mixed_tuple = (1, "Hello", 3.14, False)

2. Accessing Tuple Elements:

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')

print(letters[1:4]) # Output: ('b', 'c', 'd')


print(letters[:3]) # Output: ('a', 'b', 'c')
print(letters[::2]) # Output: ('a', 'c', '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.

• Returning 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
}

print(student_grades[("Jane", "Smith")]) # Output: 85

Common Operations with Lists and Tuples

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

3. Finding the Minimum and Maximum:

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

4. Concatenation and Repetition:

• Concatenation: Combine two sequences using the + operator.

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)

Common Program Patterns

1. Iterating Over a Sequence:

Use loops to iterate over the elements of a list or tuple.

• Using a for loop:

python
Copy
fruits = ["apple", "banana", "cherry"]

for fruit in fruits:


print(fruit)
# Output:
# apple
# banana
# cherry

• Using enumerate() to get index and value:


python
Copy
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")
# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry

2. Searching for an Item:

• Using the index() method:

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

• Handling ValueError if the item is not found:

python
Copy
try:
print(fruits.index("grape"))
except ValueError:
print("Grape is not in the list.")
# Output: Grape is not in the list.

3. Checking for All or Any Conditions:

• Using all() and any():

o all() returns True if all elements are True.

python
Copy
numbers = [1, 2, 3, 4, 5]
print(all(numbers)) # Output: True

o any() returns True if at least one element is True.

python
Copy
mixed = [0, False, None, "", 5]
print(any(mixed)) # Output: True

Nested Lists and Tuples

1. Nested Lists:

A list can contain other lists, creating a multi-dimensional data structure.

• Creating a 2D list (list of 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:

Tuples can also contain other tuples or lists.

• Creating a nested tuple:

python
Copy
point = ((3, 4), (5, 6))

• Accessing elements:

python
Copy
print(point[0]) # Output: (3, 4)
print(point[1][0]) # Output: 5

3. Mixing Lists and Tuples:

You can have lists containing tuples and vice versa.


• List of tuples:

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

1. Converting Between Lists and Tuples:

• Converting a list to a tuple:

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]

2. Converting Other Data Types to Lists or Tuples:

• Converting a string to a list:

python
Copy
string = "Hello"
list_from_string = list(string)
print(list_from_string) # Output: ['H', 'e', 'l', 'l', 'o']

• Converting a range to a list:

python
Copy
range_to_list = list(range(5))
print(range_to_list) # Output: [0, 1, 2, 3, 4]

• Converting a dictionary to a list or tuple:

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.

• List comprehensions provide a concise way to create lists.

• 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

Exercise 1: Sorting Lists

Task: Sort a list of integers in ascending and descending order.

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:

• The sort() method sorts the list in place in ascending order.

• By passing reverse=True, the list is sorted in descending order.

Exercise 2: Searching in Lists

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.

• The in keyword checks if an item is present in the list.

Exercise 3: Sorting Tuples

Task: Sort a tuple and convert it back to a tuple.

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.

Exercise 4: Accessing Elements in Nested Lists

Task: Access elements in a nested list.

Code:

python
Copy
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print("Element at row 1, column 1:", matrix[1][1])
Explanation:

• Nested lists are accessed using multiple indices.

• matrix[1][1] accesses the element at the second row and second column.

Exercise 5: Sorting a List of Tuples

Task: Sort a list of tuples based on the second element.

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.

Exercise 6: Flattening a Nested List

Task: Flatten a nested list using list comprehension.

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.

Exercise 7: Deep Copy vs. Shallow Copy

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.

• A deep copy recursively copies all nested elements.

Exercise 8: Extracting Elements from a List of Tuples

Task: Extract x-coordinates from a list of tuples.

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.

Exercise 9: Modifying a List of Tuples

Task: Replace a tuple in a list of tuples.


Code:

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.

Exercise 10: Handling Exceptions in Searching

Task: Safely search for an element in a list.

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 ().

2. How do you create a list in Python?

➢ You create a list by assigning values in square brackets, e.g., my_list = [1, 2, 3].

3. How do you access the third element of a list named my_list?

➢ You access the third element with my_list[2] since indexing starts at 0.

4. What is a list comprehension and provide an example.

➢ A list comprehension is a concise way to create lists. Example: [x**2 for x in


range(5)] creates a list of squares.

5. How do you add an element to the end of a list?

➢ Use the append() method, like my_list.append(4).

6. Why are tuples used in Python?

➢ Tuples are used when data shouldn't change, providing immutability and safety.

7. How do you create a tuple with a single element?

➢ A single-element tuple is created with a trailing comma, e.g., my_tuple = (1,).

8. What does the len() function do when applied to a list or tuple?

➢ The len() function returns the number of elements in the list or tuple.

9. How do you check if an element exists in a list?

➢ Use the in keyword, like if element in my_list:.

10. How do you convert a list to a tuple?

➢ Convert a list to a tuple using tuple(my_list).

11. How do you slice a list to get every second element?


➢ You can use slicing with a step of 2: list[::2].
12. What happens if you try to modify a tuple?
➢ Tuples are immutable, so attempting to modify them results in a TypeError.
13. How can you concatenate two lists?
➢ Use the + operator or the extend() method to combine two lists.
14. What is the difference between append() and extend() in lists?
➢ append() adds a single element to the end of the list, while extend() adds
each element of an iterable to the list.
15. Can you have a list of lists? How is that useful?
➢ Yes, lists can contain other lists, useful for representing multi-dimensional
data like matrices.
16. How do you remove an element from a list by its value?
➢ Use the remove() method: list.remove(value).
17. What is the purpose of the tuple() function?
➢ The tuple() function converts an iterable into a tuple.
18. How do you find the index of an element in a list?
➢ Use the index() method: list.index(value).
19. Can you explain the concept of immutability in tuples with an example?
➢ Immutability means tuples cannot be changed once created; for example,
you cannot add or remove elements.
20. How do you unpack values from a tuple?
➢ Assign them to variables in order: (a, b, c) = tuple.
21. What is the difference between list and tuple in terms of performance?
➢ Tuples are generally faster for operations that don't modify the data due
to their immutability.
22. How do you reverse a list?
➢ Use the reverse() method or slicing with a step of -1: list[::-1].
23. Can you sort a list of tuples? How?
➢ Yes, sort by default (first element) or specify a key using sorted() with
the key parameter.
24. What is a nested tuple and how is it used?
➢ Nested tuples contain other tuples, useful for structured data like
coordinates or records.
25. How do you convert a string into a list?
➢ Use the list() function or split the string based on a delimiter with str.split().

You might also like