Week 6: Mastering Lists - Your First Data Structure
Learn how to organize and manipulate data using lists in Python.
Explore Chapter 6List Slicing: Extracting Sublists.
Slicing is a powerful technique for creating new lists that are sub-sequences of an existing list. The syntax for slicing is `[start:stop:step]`.
- `start`: The index where the slice starts (inclusive). If omitted, defaults to 0.
- `stop`: The index where the slice ends (exclusive). If omitted, defaults to the end of the list.
- `step`: The step (or stride) between elements in the slice. If omitted, defaults to 1.
my_list = [10, 20, 30, 40, 50, 60, 70, 80]
print(my_list[1:4]) # Output: [20, 30, 40] (elements from index 1 up to, but not including, 4)
print(my_list[:3]) # Output: [10, 20, 30] (elements from the beginning up to index 3)
print(my_list[4:]) # Output: [50, 60, 70, 80] (elements from index 4 to the end)
print(my_list[:]) # Output: [10, 20, 30, 40, 50, 60, 70, 80] (a copy of the entire list)
print(my_list[1:7:2]) # Output: [20, 40, 60] (elements from 1 to 7 with a step of 2)
print(my_list[::-1]) # Output: [80, 70, 60, 50, 40, 30, 20, 10] (reversing the list)
List Comprehension (Introduction): Concise List Creation.
List comprehension provides a concise way to create new lists based on existing iterables (like lists, tuples, ranges, etc.). It's a powerful feature in Python that can make your code more readable and efficient.
Basic Syntax
new_list = [expression for item in iterable if condition]
- `expression`: The value to include in the new list.
- `item`: The variable that takes on the value of each element in the `iterable`.
- `iterable`: The sequence you want to iterate over.
- `condition` (optional): A filter to include only certain items.
Examples
# Create a list of squares of numbers from 0 to 9
squares = [x ** 2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# Create a list of even numbers from 0 to 19
even_numbers = [x for x in range(20) if x % 2 == 0] # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Create a list of uppercase versions of strings
words = ["hello", "world"]
upper_words = [word.upper() for word in words] # ["HELLO", "WORLD"]
List comprehensions can often replace `for` loops and make your code more compact, but it's important to use them judiciously to maintain readability.