Python Iterables – Looping over Iterables in Python

You’ll find iterables in almost every programming language you come across. These are important data types that you’ll probably use in 99% of the programs you’ll write. So the aim of this article is to get you acquainted with Python  iterables and how you can work with them.

We’ll also introduce you to the built-in functions that operate on iterables to make your computational tasks easier. And stick along till the end of this article to learn some additional tricks on working with iterables.

What are Python Iterables?

Iterables, as the name suggests, are objects which can be “iterated over”.

An iterable is simply a Python object which consists of a collection of data members. We can access the data members of an iterable one at a time. An iterable can be “iterated over” with a loop, like a for loop in Python.

Common examples of iterables include sequences like lists, tuples and strings. Non-sequential collections of data, like dictionaries and sets, are also examples of iterables.

In the next section, we’ll learn to use for loop to iterate over each of these iterables.

Looping over Iterables in Python

It’s worth repeating ourselves: We can loop over iterables using a for loop in Python.

Unlike other languages, Python’s for loop doesn’t require us to specify any start or stop indices to iterate over an iterable.

We can simply use the syntax below:

for item in iterable:
#do this

1. for loop on lists:

>>> odd = [1, 3, 5, 7, 9]
>>> for item in odd:
print(item)

Output:

1
3
5
7
9

2. for loop on tuples:

>>> odd = (1, 3, 5, 7, 9)
>>> for item in odd:
print(item)

Output:

1
3
5
7
9

3. for loop on strings:

>>> name = "Techvidvan"
>>> for char in name:
print(char)

Output:

T
e
c
h
v
i
d
v
a
n

4. for loop on dictionaries:

>>> superhero = { 'Steve Rogers' : 'Captain America',
'Tony Stark' : 'Iron Man',
'Peter Parker' : 'Spiderman',
'Bruce Banner' : 'Hulk'}
>>> for name in superhero:
print(name + "'s superhero name is: " + superhero[name])

Output:

Steve Rogers’s superhero name is: Captain America
Tony Stark’s superhero name is: Iron Man
Peter Parker’s superhero name is: Spiderman
Bruce Banner’s superhero name is: Hulk
>>>

5. for loop on sets:

>>> s = {1, 2, 4, 6}
>>> for item in s:
print(item)

Output:

1
2
4
6
>>>

Python Built-in functions that work on iterables

Let’s now look at some commonly used Python built-in functions that work on iterables in Python. These functions prove useful while performing computational tasks on data elements of iterables.

All these functions take an iterable as an argument and perform some operation on the elements of that iterable.

Function:

  • sum()
    Returns sum of all the elements of an iterable
  • sorted()
    Returns a list of elements of an iterable sorted in ascending order by default. You can sort in descending order by passing another argument “reverse = True” to the sorted().
  • max()
    Returns the element with the largest value in an iterable
  • min()
    Returns the element with the smallest value in an iterable

Working with Iterables – Python Tricks

While working with iterables in Python, you’ll find these two tricks the most useful. These tricks will make your code more “Pythonic”.

Iterable Unpacking

Iterable unpacking is a powerful feature while assigning values to multiple variables at the same time.

Let’s look at an example to get a better understanding.

>>> tup = (1, 2, 3)
>>> x, y, z = tup
>>> print(x, y, z)

Output:

1 2 3
>>>

Here x, y and z are the unpacking variables.

The interpreter unpacks the tuple tup and assigns tup[0], tup[1], tup[2] to x, y and z respectively. Unpacking is also useful while iterating over an iterable of iterables.v

>>> student = [(10, "Archie"), (11, "Betty"), (13,"Veronica")]
>>> for roll, name in student:
     print(name, "has the roll no.:", roll)

Output:

Archie has the roll no.: 10
Betty has the roll no.: 11
Veronica has the roll no.: 13
>>>

Here, name and roll are unpacking variables.

Enumerating iterables

Enumerating is useful when we need to keep a track of the iteration-count while looping over an iterable. We enumerate iterables using the built-in enumerate() function.

>>> for i in enumerate("Techvidvan"):
     print(i)

Output:

(0, ‘T’)
(1, ‘e’)
(2, ‘c’)
(3, ‘h’)
(4, ‘v’)
(5, ‘i’)
(6, ‘d’)
(7, ‘v’)
(8, ‘a’)
(9, ‘n’)
>>>

The enumerate() function returns a new iterable that contains tuples of the iteration-count and the corresponding item from the original iterable.

Wrapping Up!

In this article, we learned what iterables are and how can we use them to structure and loop over our data in Python. Two major takeaways from this article are:

  • You can loop over iterables using for loop in Python.
  • Iterables may or may not have indices.