Looping in Python Series
Looping in Python
For loops are used to iterate over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.
With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
for loops in Python don’t have indexes. Instead, we can use for loops to iterate over the items of any sequence, such as a list or a string.
In this tutorial, we will learn how to use for loops in Python with the help of examples. We will also learn the following:
- What is iterable in Python?
- How to use for loops in Python?
- Looping with index
- Looping over multiple iterable at once
What is iterable in Python and how to use for loop ?
An iterable is an object that can return an iterator, or one of its members. Strings, lists, tuples, and sets are all iterable objects. They are iterable containers which you can get an iterator from.
Anything you can write a for loop to iterate over is an iterable.
Manual iteration using for loop
Example 1: Iterating over a list
Let’s say we have a list of numbers and we want to print each number in the list. We can do this using a for loop.
# Example 1: Iterating over a list
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# iterate over the list
for val in numbers:
sum = sum+val
print("The sum is", sum)
Output:
sum is 48 The
Example 2: Iterating over a string
We can also iterate over a string. Here is an example to count the number of ’l’s in a string.
# Example 2: Iterating over a string
# String
= "Python"
name
# variable to store the count
= 0
count
for letter in name:
if(letter == 't'):
= count + 1
count
print('Count of t in Python is:', count)
Output:
in Python is: 1 Count of t
Example 3: Iterating over a tuple (immutable)
We can also iterate over a tuple. Here is an example to multiply all the elements of a tuple.
# Example 3: Iterating over a tuple (immutable)
# Tuple of numbers
= (1, 2, 3, 4)
numbers
# variable to store the product
= 1
result
for x in numbers:
= result * x
result
print(result)
Output:
24
All iteration utilities do the same kind of looping
The for loop is the most common way to iterate over a sequence. However, we can also use the while loop to iterate over a sequence.
The while loop is more general, since we can write any arbitrary code in its block. The for loop is more concise and Pythonic.
Example 4: Iterating over a list using while loop
# Example 4: Iterating over a list using while loop
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# iterate over the list
= 0
i
while i < len(numbers):
sum = sum + numbers[i]
= i+1
i
print("The sum is", sum)
Output:
sum is 48 The
Iterating using Constructors
We can also use the iter() function to get an iterator object and then use the next() function to iterate through it.
Example 5: Iterating using iter() and next()
# Example 5: Iterating using iter() and next()
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# get an iterator object from that iterable
= iter(numbers)
it
# iterate through it using next() function
while True:
try:
# get the next item
= next(it)
x
# do something with the item
sum = sum + x
except StopIteration:
# if StopIteration is raised, break from loop
break
print("The sum is", sum)
Output:
sum is 48 The
Looping with index
We can also loop over a sequence using the index of each item within the body of a loop using the built-in function range() and len() functions.
Example 6: Looping with index
# Example 6: Looping with index
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# iterate over the list using index
for i in range(len(numbers)):
sum = sum + numbers[i]
print("The sum is", sum)
Output:
sum is 48 The
Looping over multiple iterable at once
We can also loop over multiple iterable at once using the zip() function.
Example 7: Looping over multiple iterable at once
# Example 7: Looping over multiple iterable at once
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# List of names
= ['John', 'Paul', 'George', 'Ringo']
names
# iterate over two lists simultaneously
for i, j in zip(numbers, names):
print(i, j)
Output:
6 John
5 Paul
3 George
8 Ringo
Looping in reverse
We can loop over a sequence in reverse using the reversed() function.
Example 8: Looping in reverse
# Example 8: Looping in reverse
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# iterate in reverse
for num in reversed(numbers):
print(num)
Output:
11
4
5
2
4
8
3
5
6
Looping over a dictionary
We can loop over a dictionary using a for loop. By default, iterating over a dictionary will loop over its keys. However, we can use the values() or items() methods to access the values or both keys and values.
Example 9: Looping over a dictionary
# Example 9: Looping over a dictionary
# Dictionary
= {'x': 1, 'y': 2, 'z': 3}
d
# Iterate over dictionary keys
for key in d:
print(key, 'corresponds to', d[key])
Output:
1
x corresponds to
2
y corresponds to
3 z corresponds to
Example 10: Looping over dictionary keys and values
# Example 10: Looping over dictionary keys and values
# Dictionary
= {'x': 1, 'y': 2, 'z': 3}
d
# Iterate over dictionary keys and values
for key, value in d.items():
print(key, 'corresponds to', d[key])
Output:
1
x corresponds to
2
y corresponds to
3 z corresponds to
Example 11: Looping over dictionary keys and values using iteritems()
# Example 11: Looping over dictionary keys and values using iteritems()
# Dictionary
= {'x': 1, 'y': 2, 'z': 3}
d
# Iterate over dictionary keys and values
for key, value in d.iteritems():
print(key, 'corresponds to', d[key])
Output:
1
x corresponds to
2
y corresponds to
3 z corresponds to
Looping over a string
We can loop over a string using a for loop. By default, iterating over a string will loop over its characters.
Example 12: Looping over a string
# Example 12: Looping over a string
# String
= "John"
name
# Iterate over string characters
for char in name:
print(char)
Output:
John
Looping over a file
We can loop over a file using a for loop. By default, iterating over a file will loop over its lines.
Example 13: Looping over a file
# Example 13: Looping over a file
# Open file for reading
with open('test.txt', 'r') as f:
# Loop over each line of the file
for line in f:
# process the line
print(line)
Output:
!
Hello World
is our new text file
This
and this is another line.
Looping with else
We can use the else clause in a for loop to execute a block of code once when the loop has exhausted iterating the list.
Example 14: Looping with else
# Example 14: Looping with else
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# iterate over the list
for num in numbers:
sum = sum + num
else:
print("Inside else")
print("The sum is", sum)
Output:
else
Inside
sum is 48 The
Nested loops
We can use one or more for loops inside another for loop. These are called nested loops.
Example 15: Nested loops
# Example 15: Nested loops
# List of numbers
= [6, 5, 3, 8, 4, 2, 5, 4, 11]
numbers
# variable to store the sum
sum = 0
# iterate over the list
for num in numbers:
sum = sum + num
for i in range(2):
sum = sum + i
print("The sum is", sum)
Output:
sum is 66 The
loop using
looping using constructor
A for loop isn’t the only way to iterate over an iterable.
A list constructor does iteration as well. “,
“Here’s an example of using a list constructor to iterate over a string:”,
“```python”,
“for char in list(‘hello’):”,
” print(char)“,
“```”,
“Output:”,
“```python”,
“h”,
“e”,
“l”,
“l”,
“o”,
“```”,
“## loop using enumerate”,
“Another way to iterate over an iterable is to use the enumerate() function. ”,
“enumerate() returns a tuple containing a count (from start which defaults to 0) ”,
“and the values obtained from iterating over the iterable.”,
“Here’s an example of using enumerate() to iterate over a string:”,
“```python”,
“for i, char in enumerate(‘hello’):”,
” print(i, char)“,
“```”,
“Output:”,
“```python”,
“0 h”,
“1 e”,
“2 l”,
“3 l”,
“4 o”,
“```”,
“## loop using zip”,
“Another way to iterate over iterables is to use the zip() function. ”,
“zip() returns an iterator of tuples, where the i-th tuple contains the i-th element ”,
“from each of the argument sequences or iterables.”,
“Here’s an example of using zip() to iterate over two lists:”,
“```python”,
“for i, j in zip([1, 2, 3], [4, 5, 6]):”,
” print(i, j)“,
“```”,
“Output:”,
“```python”,
“1 4”,
“2 5”,
“3 6”,
“```”,
“## loop using reversed”,
“Another way to iterate over an iterable is to use the reversed() function. ”,
“reversed() returns a reverse iterator. ”,
“Here’s an example of using reversed() to iterate over a string:”,
“```python”,
“for char in reversed(‘hello’):”,
” print(char)“,
“```”,
“Output:”,
“```python”,
“o”,
“l”,
“l”,
“e”,
“h”,
“```”,
“## loop using sorted”,
“Another way to iterate over an iterable is to use the sorted() function. ”,
“sorted() returns a new sorted list from the items in iterable.”,
“Here’s an example of using sorted() to iterate over a string:”,
“```python”,
“for char in sorted(‘hello’):”,
” print(char)“,
“```”,
“Output:”,
“```python”,
“e”,
“h”,
“l”,
“l”,
“o”,
“```”,
“## loop using map”,
“Another way to iterate over an iterable is to use the map() function. ”,
“map() applies a function to all the items in an input_list.”,
“Here’s an example of using map() to iterate over a list:”,
“```python”,
“def add_one(x):”,
” return x + 1“,
“for i in map(add_one, [1, 2, 3, 4, 5]):”,
” print(i)“,
“```”,
“Output:”,
“```python”,
“2”,
“3”,
“4”,
“5”,
“6”,
“```”,
“## loop using filter”,
“Another way to iterate over an iterable is to use the filter() function. ”,
“filter() constructs an iterator from those elements of iterable for which function returns true.”,
“Here’s an example of using filter() to iterate over a list:”,
“```python”,
“def is_even(x):”,
” return x % 2 == 0“,
“for i in filter(is_even, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]):”,
” print(i)“,
“```”,
“Output:”,
“```python”,
“2”,
“4”,
“6”,
“8”,
“10”,
“```”,
“## loop using reduce”,
“Another way to iterate over an iterable is to use the reduce() function. ”,
“reduce() applies a rolling computation to sequential pairs of values in a list.”,
“Here’s an example of using reduce() to iterate over a list:”,
“```python”,
“from functools import reduce”,
“def add(x, y):”,
” return x + y“,
“print(reduce(add, [1, 2, 3, 4, 5]))”,
“```”,
“Output:”,
“```python”,
“15”,
“```”,
“## loop using itertools”,
“Another way to iterate over an iterable is to use the itertools module. ”,
“itertools is a standard library that contains several functions that are useful in functional programming.”,
“Here’s an example of using itertools to iterate over a list:”,
“```python”,
“import itertools”,
“for i in itertools.chain([1, 2, 3], [4, 5, 6]):”,
” print(i)“,
“```”,
“Output:”,
“```python”,
“1”,
“2”,
“3”,
“4”,
“5”,
“6”,
“```”,
“## loop using operator”,
“Another way to iterate over an iterable is to use the operator module. ”,
“operator is a standard library that contains the implementation of intrinsic operators in Python.”,
“Here’s an example of using operator to iterate over a list:”,
“```python”,
“import operator”,
“for i in map(operator.add, [1, 2, 3], [4, 5, 6]):”,
” print(i)“,
“```”,
“Output:”,
“```python”,
“5”,
“7”,
“9”,
“```”,
“## loop using functools”,
“Another way to iterate over an iterable is to use the functools module. ”,
“functools is a standard library that contains several higher order functions and operations on callable objects.”,
“Here’s an example of using functools to iterate over a list:”,
“```python”,
“import functools”,
“for i in map(functools.partial(operator.add, 1), [1, 2, 3, 4, 5]):”,
” print(i)“,
“```”,
“Output:”,
“```python”,
“2”,
“3”,
“4”,
“5”,
“6”,
“```”,
“## loop using zip”,
“Another way to iterate over an iterable is to use the zip() function. ”,
“zip() returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.”,
“Here’s an example of using zip() to iterate over two lists:”,
“```python”,
“for i, j in zip([1, 2, 3], [4, 5, 6]):”,
” print(i, j)“,
“```”,
“Output:”,
“```python”,
“1 4”,
“2 5”,
“3 6”,
“```”,
“## loop using enumerate”,
Looping with index
“Another way to iterate over an iterable is to use the enumerate() function. ”,
“enumerate() returns an enumerate object. It contains the index and value of all the items in the list as pairs.”,
“Here’s an example of using enumerate() to iterate over a list:”,
“```python”,
“for i, j in enumerate([1, 2, 3, 4, 5]):”,
” print(i, j)“,
“```”,
“Output:”,
“```python”,
- Dictionaries, generators and files are also iterables. There are lots of other iterables in the Python, both built-in and included in third-party libraries.