del statement.append(), insert(), remove(), reverse() and copy().filter(), map() and reduce().A sequence is an ordered collection of values. Python provides several sequence types, including strings, lists and tuples. This chapter focuses especially on lists and tuples and shows how to store, access, modify, search and process collections of data.
A list is an ordered collection written with square brackets []. Lists can contain values of the same type or different types, and they can grow or shrink while a program runs.
numbers = [-45, 6, 0, 72, 1543] print(numbers)
List indexing starts at 0.
numbers = [10, 20, 30, 40, 50] print(numbers[0]) print(numbers[2]) print(numbers[-1])
| Index | Value |
|---|---|
| 0 | 10 |
| 1 | 20 |
| 2 | 30 |
| 3 | 40 |
| 4 | 50 |
numbers = [10, 20, 30] numbers[1] = 99 print(numbers)
The chapter emphasizes that list elements can be modified and that lists can also grow and shrink.
IndexError. Using a non-integer index causes TypeError.values = []
for number in range(1, 6):
values += [number]
print(values)A tuple is another sequence type. It is similar to a list for accessing elements, but the tuple itself is immutable.
student = ('Amanda', 'Blue', 98)
print(student[0])
print(student[2])numbers = (10, 20, 30) # numbers[0] = 99 # TypeError
A tuple can contain a list. The tuple itself remains immutable, but the list inside it can still be modified.
student = ('Amanda', 'Blue', [98, 75, 87])
student[2][1] = 85
print(student)The source demonstrates this distinction: the tuple structure is unchanged, but its nested list can be modified.
Unpacking means assigning the elements of a sequence to separate variables.
student = ('Amanda', [98, 85, 87])
first_name, grades = student
print(first_name)
print(grades)You can unpack strings, lists, tuples and sequences produced by range(). The number of variables must match the number of elements, otherwise Python raises ValueError.
first, second = 'hi' print(first, second) a, b, c = range(10, 40, 10) print(a, b, c)
Slicing creates a new sequence containing a selected part of the original sequence. The basic form is:
sequence[start:stop]
The start index is included, but stop is excluded. The original list is not modified by an ordinary slice operation.
numbers = [2, 3, 5, 7, 11, 13, 17, 19] print(numbers[2:6]) print(numbers[:6]) print(numbers[4:]) print(numbers[::2])
| Slice | Meaning |
|---|---|
numbers[2:6] | Index 2 up to, but not including, 6 |
numbers[:6] | Beginning through index 5 |
numbers[4:] | Index 4 through the end |
numbers[::2] | Every second element |
numbers[::-1] | Reverse order |
The del statement can delete individual list elements, slices or even a variable.
numbers = list(range(10)) del numbers[-1] print(numbers) del numbers[0:2] print(numbers)
numbers = list(range(10)) del numbers[::2] print(numbers)
numbers = [1, 2, 3] del numbers[:] print(numbers)
The source also demonstrates that del numbers removes the variable itself; attempting to use it afterward causes NameError.
Lists are mutable objects. When a list is passed to a function, the function receives a reference to that list. Therefore, modifying its elements inside the function changes the original list.
def modify_elements(items):
for i in range(len(items)):
items[i] *= 2
numbers = [10, 3, 7, 1, 9]
modify_elements(numbers)
print(numbers)TypeError, because tuples are immutable.Sorting arranges elements into an order, usually ascending or descending.
numbers = [7, 2, 9, 1, 5] numbers.sort() print(numbers) numbers.sort(reverse=True) print(numbers)
numbers = [7, 2, 9, 1, 5] ordered = sorted(numbers) print(ordered) print(numbers)
list.sort() sorts the existing list. sorted() returns a new sorted result.Python provides several simple ways to search a sequence.
colors = ['red', 'green', 'blue']
print('green' in colors)
print('yellow' not in colors)colors = ['red', 'green', 'blue', 'green']
print(colors.index('green'))index() returns the position of the first matching element.
colors = ['red', 'green', 'blue', 'green']
print(colors.count('green'))in answers "is it present?", index() answers "where is the first one?", and count() answers "how many are there?".| Method | Purpose | Example |
|---|---|---|
append(x) | Adds one item at the end | items.append(10) |
insert(i, x) | Inserts at a position | items.insert(1, 10) |
remove(x) | Removes the first matching item | items.remove(10) |
reverse() | Reverses the list | items.reverse() |
copy() | Creates a shallow copy | new = items.copy() |
items = [10, 20, 30] items.append(40) items.insert(1, 15) items.remove(30) print(items) items.reverse() print(items)
A stack follows LIFO: Last In, First Out. The most recently added item is the first one removed.
stack = []
stack.append('A')
stack.append('B')
stack.append('C')
print(stack.pop())
print(stack.pop())
print(stack)A list comprehension is a concise way to create a new list from an iterable.
squares = [x ** 2 for x in range(1, 6)] print(squares)
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6] odd_squares = [x ** 2 for x in numbers if x % 2 != 0] print(odd_squares)
Generator expressions look like list comprehensions, but use parentheses instead of square brackets.
numbers = [10, 3, 7, 1, 9]
squares_of_odds = (x ** 2 for x in numbers if x % 2 != 0)
for value in squares_of_odds:
print(value, end=' ')A generator expression produces values on demand instead of creating the complete list immediately. This can reduce memory use when the whole list is not needed at once.
Functional-style programming provides ways to process collections.
filter() keeps values for which a function returns True.
def is_odd(x):
return x % 2 != 0
numbers = [10, 3, 7, 1, 9, 4, 2, 8, 5, 6]
print(list(filter(is_odd, numbers)))The chapter describes filter() as a higher-order-function capability: functions themselves can be passed as arguments.
map() applies a function to each value.
numbers = [1, 2, 3, 4, 5] squares = list(map(lambda x: x ** 2, numbers)) print(squares)
A reduction processes many values into a single value, such as a total, product, minimum or maximum. Python's functools.reduce() can be used for custom reductions.
from functools import reduce numbers = [1, 2, 3, 4] total = reduce(lambda x, y: x + y, numbers) print(total)
filter → selectmap → transformreduce → combine into one resultPython provides many built-in functions that work with sequences. Common examples include len(), sum(), min(), max(), any(), all() and enumerate().
enumerate() is especially useful when you need both an element and its index.
colors = ['red', 'green', 'blue']
for index, value in enumerate(colors):
print(index, value)numbers = [1, 2, 3, 4]
for value in reversed(numbers):
print(value, end=' ')numbers = [10, 3, 7, 1, 9] print(min(numbers)) print(max(numbers)) print(sum(numbers))
A two-dimensional list is a list containing other lists. It is useful for representing data arranged in rows and columns, such as a table or matrix. The chapter processes these structures with nested for loops.
grades = [
[88, 92, 95],
[76, 85, 90],
[91, 89, 94]
]
for row in grades:
for value in row:
print(value, end=' ')
print()print(grades[1][2])
Think of grades[row][column] as: first choose the row, then choose the item inside that row.
This chapter moves from simply storing data to visualizing it. It uses Seaborn and Matplotlib to create static bar charts showing the results of a six-sided-die simulation. Seaborn is built on Matplotlib and simplifies many plotting operations.
import random
rolls = [random.randrange(1, 7) for _ in range(600)]
frequencies = [
rolls.count(face)
for face in range(1, 7)
]
print(frequencies)For a fair six-sided die, each face should appear approximately one-sixth of the time. With only 600 rolls, frequencies will not be exactly equal. As the number of rolls becomes much larger, the percentages become closer to the expected value of about 16.667% for each face.
import matplotlib.pyplot as plt
import seaborn as sns
faces = list(range(1, 7))
sns.barplot(x=faces, y=frequencies)
plt.title('Die Frequencies')
plt.xlabel('Die Value')
plt.ylabel('Frequency')
plt.show()The source chapter uses Seaborn and Matplotlib together to develop a static bar plot of die frequencies.
With 600 rolls, the bars can differ noticeably. With 60,000 rolls they become much closer in size, and with 6,000,000 rolls they appear nearly equal. This illustrates the law of large numbers: as the number of trials increases, observed percentages tend to get closer to expected probabilities.
The chapter also shows how a script can receive the number of die rolls from the command line through the Standard Library's sys module.
import random
import sys
rolls = [
random.randrange(1, 7)
for _ in range(int(sys.argv[1]))
]For example, running a script with a value such as 600 makes that value available through sys.argv. The chapter notes that command-line arguments arrive as strings, so the roll count is converted with int().
The chapter compares simulations at three scales. With more rolls, the frequencies and percentages of the six faces become increasingly similar. This is a practical demonstration of probability becoming more stable over many trials.
| Rolls | What you should expect |
|---|---|
| 600 | Noticeable differences between face frequencies. |
| 60,000 | Frequencies become much closer. |
| 6,000,000 | Bars appear nearly equal. |
A good visualization should make the data easy to understand. The chapter's static visualization includes a title, x-axis label, y-axis label, bars for the die values and frequency/percentage information.
This chapter develops lists and tuples in detail: creating them, accessing elements, modifying lists, slicing sequences, deleting elements, passing collections to functions, sorting and searching, and using list methods.
It also introduces stacks, list comprehensions, generator expressions, filtering and mapping, two-dimensional lists, and static data visualization.
0.numbers[2:6] with including index 6 — the stop index is excluded.del numbers when you only intended to clear the list.sort() with sorted().index() for an item that is not present.filter, map and reduce.start:stop:step.-1 mean?del do?sort() and sorted()?in, index() and count() differ?filter(), map() and reduce().append() and pop().filter() to select even numbers.map() to convert Celsius temperatures to Fahrenheit.Teaching note: This HTML is a beginner-friendly transformative explanation based on the chapter's concepts and structure. It is designed for learning and revision rather than reproducing the book's original text.