Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding for loops in Python

I'm trying to create a for loop and I ran into problems. I don't understand how these loops work, and I think the problem is because I'm using the for syntax incorrectly.

From what I understand, a for loop should look like

for w in words:
    print(w, len(w))

But how exactly does it work?

To try to be specific: What does the w mean? How can I know what to write between for and in, and after in? What exactly happens when the code runs?


For a more technical breakdown of how for loops are implemented, see How does a Python for loop with iterable work?.

like image 260
musha1 Avatar asked Sep 18 '25 20:09

musha1


2 Answers

A for loop takes each item in an iterable and assigns that value to a variable like w or number, each time through the loop. The code inside the loop is repeated with each of those values being re-assigned to that variable, until the loop runs out of items.

Note that the name used doesn't affect what values are assigned each time through the loop. Code like for letter in myvar: doesn't force the program to choose letters. The name letter just gets the next item from myvar each time through the loop. What the "next item" is, depends entirely on what myvar is.

As a metaphor, imagine that you have a shopping cart full of items, and the cashier is looping through them one at a time:

for eachitem in mybasket: 
    # add item to total
    # go to next item.

If mybasket were actually a bag of apples, then eachitem that is in mybasket would be an individual apple; but if mybasket is actually a shopping cart, then the entire bag could itself meaningfully be a single "item".

like image 189
beroe Avatar answered Sep 20 '25 10:09

beroe


A for loop works on an iterable: i.e., an object that represents an ordered collection of other objects (it doesn't have to actually store them; but most kinds of iterable, called sequences, do). A string is an iterable:

>>> for c in "this is iterable":
...     print(c, end=" ")
...
t  h  i  s     i  s     i  t  e  r  a  b  l  e 

However, a number is not:

>>> for x in 3:
...     print("this is not")
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable

The built-in range function allows an easy way to iterate over a range of numbers:

>>> for x in range(3):
...     print(x)
...
0
1
2

In 2.x, range simply creates a list with those integer values; in 3.x, it makes a special kind of object that calculates the numbers on demand when the for loop asks for them.

like image 38
Freddie Avatar answered Sep 20 '25 08:09

Freddie