3.5.1 Built-in Data Structures Compared
Python provides several built-in data structures that are essential for organizing and manipulating data efficiently. These include lists, tuples, and dictionaries, each offering unique features to handle various types of data and perform common operations.
Lists
In Python, a list is a versatile data structure that can hold a collection of items. You can create, access, and modify lists easily.
Creating, Accessing, and Modifying Lists
A list is created by placing items inside square brackets [], separated by commas. Lists can contain items of different types, such as numbers, strings, or even other lists.
Example: Create a list of your favorite fruits.
fruits = ["Mango", "Apple", "Banana"]
print(fruits)
# Output: ['Mango', 'Apple', 'Banana']
Accessing List Items
You can access items in a list by referring to their index, starting from .
Example: Access and print the second item from the list of fruits.
fruits = ["Mango", "Apple", "Banana"]
print(fruits[1])
# Output: Apple
Explanation: The code initializes a list fruits containing 'Mango', 'Apple', and 'Banana', then prints the second item, 'Apple', using the index 1.
Modifying a List
You can modify list items by accessing them via their index and assigning a new value.
Example: Change the first item in the list to "Orange" and add a new fruit "Pineapple".
fruits = ["Mango", "Apple", "Banana"]
fruits[0] = "Orange"
fruits.append("Pineapple")
print(fruits)
# Output: ['Orange', 'Apple', 'Banana', 'Pineapple']
Explanation: The code modifies the first element of the 'fruits' list to 'Orange', appends 'Pineapple' at the end, and prints the updated list.
Methods and Operations on Lists
Python provides several built-in methods to work with lists. Here are a few useful ones:
append(item)- Adds an item to the end of the list.remove(item)- Removes the first occurrence of an item from the list.sort()- Sorts the list in ascending order.reverse()- Reverses the order of the list.
Example: Add a new student to the list of students and then sort the list.
students = ["Ahmed", "Sara", "Ali"]
students.append("Hina")
students.sort()
print(students)
# Output: ["Ahmed", "Ali", "Hina", "Sara"]
Explanation: The code creates a list of students, adds 'Hina' to it, and sorts the list alphabetically.
List Operations
Lists also support various operations, such as slicing and concatenation.
Example: Slice a portion of the list and concatenate it with another list.
numbers = [1, 2, 3, 4, 5]
slice = numbers[1:4] # Gets items from index 1 to 3
extra_numbers = [6, 7]
combined = slice + extra_numbers
print(combined)
# Output: [2, 3, 4, 6, 7]
Explanation: The code slices the 'numbers' list from index to , combines it with 'extra_numbers', and prints the resulting list '[2, 3, 4, 6, 7]'.
Example: Sort a list of student names and remove a specific name.
student_names = ["Ahmed", "Sara", "Ali", "Hina"]
student_names.sort()
student_names.remove("Sara")
print(student_names)
# Output: ["Ahmed", "Ali", "Hina"]
Explanation: The code sorts the list 'student_names' alphabetically, removes 'Sara' from the list, and then prints the updated list.
Class Activity
Imagine you are maintaining a list of your favorite books: ["To Kill a Mockingbird", "1984", "The Great Gatsby", "Pride and Prejudice"]. Perform the following tasks using Python:
- Add a new book "Moby Dick" to the list.
- Replace "1984" with "Brave New World".
- Remove "The Great Gatsby" from the list.
- Merge this list with another list of books:
["War and Peace", "Hamlet"]. - Print the final list of books.
Tidbits
lightbulbUse list methods like
append()andremove()to efficiently manage and modify your lists. For larger projects, organizing data in lists helps keep your code clean and manageable.
Tuples
In Python, tuples are a type of data structure used to store an ordered collection of items, similar to lists, but with a key difference: tuples are immutable, meaning their values cannot be changed after creation.
Example
# Creating a tuple
my_tuple = (1, 2, 3, "Hello", 4.5)
# Accessing elements by index
print(my_tuple[0]) # Output: 1
print(my_tuple[3]) # Output: Hello
# Tuple length
print(len(my_tuple)) # Output: 5
Indexing and Slicing
Indexing and slicing are essential techniques in Python for accessing and manipulating sequences such as lists, tuples, and strings.
Indexing
Indexing allows you to access individual elements in a sequence. Python uses zero-based indexing, meaning the first element has an index of , the second element has an index of and so on.
Slicing
Slicing allows you to access a subset of a sequence. The syntax for slicing is sequence[start:stop:step], where start is the starting index, stop is the ending index (not inclusive), and step is the step size.
Indexing and Slicing with Negative Indices
Negative indices count from the end of the sequence. For example, refers to the last element, refers to the second last element, and so on.
Example: Indexing and slicing with both positive and negative indices on a list.
# Create a list of fruits
fruits = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]
# Indexing
print("First fruit:", fruits[0]) # Positive index
print("Last fruit:", fruits[-1]) # Negative index
# Slicing with positive indices
print("Fruits from index 1 to 3:", fruits[1:4])
# Slicing with negative indices
print("Fruits from index -4 to -1:", fruits[-4:-1])
Explanation: This code demonstrates list operations in Python: creating a list of fruits, accessing elements using positive and negative indexing, and slicing the list with both positive and negative indices.
Class Activity
Consider the following list, tuple, and string:
- List:
[10, 20, 30, 40, 50, 60, 70, 80] - Tuple:
("Math", "Science", "English", "History", "Geography") - String:
"Python Programming"
Perform the following operations:
- Access and print the third element from each sequence (list, tuple, and string).
- Slice and print elements from index to from the list and the tuple.
- Slice and print characters from index to the end of the string.
- Use negative indexing to print the last two elements from the list and the tuple.
- Use negative slicing to print characters from the second last to the last character of the string.
Write the Python code to perform these operations and print the results.
Tidbits
lightbulbIndexing and slicing are powerful tools for working with sequences in Python. Practice these techniques to become more proficient in manipulating data and accessing specific parts of sequences.