How to Loop over a List in Python

Lists are cool, and one of the first things you’re going to want to do is loop over a list. The  diagram below that breaks down how each part of this type of loop works:python-loop-over-list-foreach-diagram-border

Now, this type of loop is called a foreach loop, and it’s a straightforward way to gain access to each element in the list.

Let’s look at example code that prints out each item in a list  that we called animals  below:

Example Code 1


We could have used any valid variable name in place of animal . For instance the sample code below leads to the exact same output:

Example Code 2


If you run codes above,  you’ll see that the both produce the same console output:


Since both codes work, which one is better?

Well, the only difference is whether we call the variable animal or x.

And the first code set with animal is definitely better because the word animal  is more descriptive.