Skip to content
Home » Iterating over Indices in Python

Iterating over Indices in Python

Spread the love

In one of my previous articles we were talking about iterating over ranges. Today we’ll learn how to use the range function to iterate over the indices of a sequence.

You can use the range function if you want to iterate over the indices of a sequence. All you have to do is pass the length of the sequence as the argument to the range function:

 cars = ["Porsche", "Chevrolet", "Peugeot", "Honda"]
  
 for index in range(len(cars)):
     print(cars[index] + " is at index " + str(index) + ".") 

And here’s the output:

 Porsche is at index 0.
 Chevrolet is at index 1.
 Peugeot is at index 2.
 Honda is at index 3. 

Here the length of the list is 4 and range(4) generates the numbers 0, 1, 2 and 3, which are the indices in the list.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.


Spread the love
Tags:

Leave a Reply