Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

list
python
communitycreator

How to loop through a list using the index numbers in Python

Onyejiaku Theophilus Chidalu

Overview

A list in Python is a data structure that consists of a changeable or mutable ordered sequence of elements. Each element or value present in the list is called an item. In Python, lists are defined by putting their items between square brackets [ ].

Example

countries = ["USA", "CHINA", "TURKEY"]

In the example above, countries is a list variable, while "USA", "CHINA" and "TURKEY" are all items of the list.

How to loop through a list in Python

To loop through a list in Python simply means repeating something over and over in the list until a particular condition is satisfied.

We can loop through a list in Python by referring to the index numbers of the elements of the list. In this case, all we need are the range() and len() functions to create a suitable iterable.

The range() function

The range() function in Python is used to iterate over a sequence type such as a list, a string, etc., with for and while loops.

Syntax

range(start, stop[, step])

The len() function

The len() function returns the length of a list, string, dictionary, or any other iterable data format in Python. In simpler terms, we use the len() function to determine the length of the list we created.

Syntax

len(iterable_object)

The range(len(iterable)) function

The combination of the range() and len() functions, (range(len(iterable), is used to iterate over a list in Python. Using the two functions together, we can refer to the index numbers of all items or elements in a list.

Code

In the example below, we will print all the items or elements of the list by simply referring to their index numbers.

# creating a list
countries = ["USA", "CHINA", "BRAZIL", "TURKEY"]

# referring to their index numbers using the range(len(iterable))
for i in range(len(countries)):
  print(countries[i])
Looping through a list by referring to their index numbers

Explanation

  • Line 2: We create a list countries.
  • Line 5: We create a for loop and, using the range(len(iterable)) function, we refer to respective index numbers of all the items present in the list and create an iteration over all the items.
  • Line 6: We print all the items of the list.

The iterable we create in the code above is [0, 1, 2, 3].

RELATED TAGS

list
python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring