Python List Operations: Iteration, Numerical Lists, and Slicing
Iterating Through an Entire List
The For Loop
You can use a for loop to iterate through every element in a list.
names = ['Huang Wei', 'nB', 'apple', 'DDD']
for item in names:
print(item)
print(type(item))
print(item) # This prints the last item after the loop finishes
Output:
Huang Wei
<class 'str'>
nB
<class 'str'>
apple
<class 'str'>
DDD
<class 'str'>
DDD
Note: The
forloop only repeats the indented statements immediate folowing it. The colon (:) at the end of theforstatement tells Python that the next line is the first line of the loop body.
Creating Numerical Lists
1. The range() Function
The range() function can be used to easily generate a sequence of numbers.
for num in range(1, 6):
print(num, end="\t")
Output: 1 2 3 4 5
Note: The number 6 is not printed. The
range(start, stop)function counts fromstartup to, but not including,stop.
range(stop): Starts from 0. Example:range(6)returns0, 1, 2, 3, 4, 5.range(start, stop, step): Alllows specifying a step size. Example:range(1, 6, 2)returns1, 3, 5.
2. Creating a List with range()
You can convert the output of range() directly into a list using the list() function.
numbers = list(range(1, 6, 2))
print(numbers)
Output: [1, 3, 5]
Example: How too create a list containing the squares of numbers from 1 to 10.
squares = []
for i in range(1, 11):
squares.append(i ** 2)
print(squares)
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
3. Simple Statistical Operations on Numerical Lists
You can use built-in functions like min(), max(), and sum() on lists of numbers.
num_list = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print(min(num_list))
print(max(num_list))
print(sum(num_list))
4. List Comprehensions
A list comprehension combines the for loop and the code for creating new elements into a single line, automatically appending each new element.
squares = [value ** 2 for value in range(1, 11)]
print(squares)
Output: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Note: The
forstatement inside the list comprehension does not end with a colon.
Working with Parts of a List
1. Slicing
To create a slice, you specify the index of the first element you want and the index of the element after the last element you want. The slice stops before raeching the second index.
names = ['Huang Wei', 'nB', 'apple', 'DDD']
print(names[0:3])
Output: ['Huang Wei', 'nB', 'apple']
Corresponding Indices: 0, 1, 2
print(names[-3:])
Output: ['nB', 'apple', 'DDD']
Explanation: The slice
[-3:]starts from the third element from the end and goes to the end of the list.