How does a program know what 'item' is?

Hey coders,

I’m doing the basics of Python and I often come up with code like this:

for item in list:
  print item

But, when I look at the code, I never see item defined. So how does the program know what item is? Is there some sort of code behind the code that defines all this? Or . . . what?

I’m just curious, but sometimes it’s confusing :roll_eyes:

Anyways . . . thanks y’all!


1 Like

Python will take care of it for you. Inside the loop block python makes sure “item” is defined. Python handles iterating over your list and pointing at the proper “item”.

I don’t know exactly how it is implemented and that’s a good thing. We want a level of abstraction for easy to use methods/constructs.


Ok, thanks! That makes things clearer :+1:

1 Like

The for-statement has three blanks of sorts for you to fill out. You provide something that is iterable (in this case a list), and a name (or multiple names if you destructure the value) and then one or more statements which are to be repeated.

So you’re the one defining it. Otherwise you wouldn’t need to mention it in the loop header.

As for how the iteration itself happens, that is up to the value that you are iterating over. This relies on a number of relatively advanced features, but for most purposes it should satisfy you that lists and other values have the behaviour of being iterable.

Since I mentioned destructuring I should show what I mean by that. Iterable values can be unpacked, like so:

a, b = (1, 2)  # a is assigned to 1, b is assigned to 2

# one use is for swapping variables around:
a, b = b, a  # same thing, the parentheses aren't required to make a tuple, it's actually the comma that does it!

# or perhaps you're only interested in the first two and the last values:
[a, b, *_, c] = [1, 2, 3, 4, 5]
print(a, b, c)  # 1 2 5
print(_)  # this'll have the value [3, 4], the underscore name isn't special, it's just a name sometimes used to say that this is ignored/uninteresting
# you can unpack into lists too:
[1, 2, *[3, 4, 5], 6]  # [1, 2, 3, 4, 5, 6]
# ...and dicts
{1:2, **{3: 4}}  # {1:2, 3:4}

for a, b in [(1, 2), (3, 4)]:
    print(a + b)  # iteration1: 3, iteration2: 7

The behaviour of an iterable value is that when asked for it, it returns an iterator. That iterator is then in turn repeatedly asked for next value until exhausted.

iterable_value = [1, 2]
iterator = iter(iterable_value)  # ask for iterator
value1 = next(iterator)  # ask iterator for next value
value2 = next(iterator)  # ask iterator for next value
value3 = next(iterator)  # error, iterator exhausted, that's how the for-statement knows to exit
1 Like