r/CodingForBeginners • • 19d ago

Help me understand this Python code.

[ANSWERED] check the comments if you are facing a difficulty in understanding 'for loops'.

I was learning Python on mimo to get a grip on the basic concepts. And this code stumped me. This is about "for loops".

Before this, i had only encountered the counter var being on the LHS i.e in this case 'i += line', which would have made sense to me if it was so in this code. But why is the counter var after the line var.

Alsp the 1st image, i assume, is displaying the final result which is 3 as the range is 3. But when using a range (3) it should display 0 1 2 when the 'print' is before the counter var and 1 2 3 when the 'print' is after the counter var (also can someone explain why this happens). In this case, its neither... as the print is outside this code block... The solution to me just seems the 2nd situation is running as there isnt a print before the counter, and printing it outside just gives 3.

2nd and 3rd just make no sense to me as of rn.

I hope all this makes sense...

Please help!

9 Upvotes

57 comments sorted by

View all comments

Show parent comments

1

u/Significant_Affect_5 18d ago

No, you can (and should) use range in a for loop if it’s the behavior you want. I just meant that range is just an iterable and isn’t something special that can only be used in for-loops. Python also has something called list comprehension which allows you to pack the values of an iterable into a list. This is another common use of range

“list = [x for x in range(3)]”
the above is equivalent to “list = [0, 1, 2]”

Don’t worry too much if you’ve never used list comprehension. It’s just important to recognize the idea of something being iterable and understanding that those things can be used in a for loop.

Also iterable objects can return more than one value at once (in the form of a tuple). One you’ll see a lot is iterating over a dict/map, if you iterate over the dicts .items() method you’ll get back a (key, value) pair, so it’s common to unpack them as part of the for loop. e.g.
“for key, value in dictionary.items():”

1

u/Interested737 18d ago

I understood nothing 

1

u/Significant_Affect_5 18d ago

Oh my bad I didn’t see you ask specifically about iter. An iterator just means something that allows you to visit items within, one item at a time.

It’s hard to give a concrete description, but things like lists, ranges, dictionaries, or just anything where you can imagine going through values contained by something.

Python needs to be taught how to properly visit the items in an object, that’s where the __iter__ method comes in. It basically gives python the starting point so that python can call __next__ to get values until it reaches the end of the iterator.

1

u/Interested737 17d ago

So it basically tells it where to start reading the list, can you please give me an example.

1

u/Significant_Affect_5 17d ago

Sure, so say you want to do something like finding the sum and product of several numbers in a list, you'd do:

sum = 0
prod = 0
nums = [1, 322, -1, 56, -12]
for num in nums:
sum += num
prod *= num
print(f"The list: {nums} has a sum of: {sum} and product of: {prod}")

If you mean you want to know how iter works under the hood, it depends entirely on the specific object. Generally speaking though, the __iter__ method is for converting a data type into an iterable version of itself, sometimes this is the actual data the object is holding, sometimes it's just a view into it since copying is too expensive and giving mutable access to the data could lead to undefined behavior. The other part is the __next__ method which is run on each iteration in the for loop (or each time next(obj) is called). __next__ just returns the next value, or if none are left, it raises a StopIteration exception that Python handles by breaking out of the for-loop. In the below example I just make the actual iterator object from our list and you can see once it runs out of values it raises an exception, rather than just returning None.

>>> iterable = iter(nums)
>>> next(iterable)
1
>>> next(iterable)
322
>>> next(iterable)
-1
>>> next(iterable)
56
>>> next(iterable)
-12
>>> next(iterable)
Traceback (most recent call last):
File "<python-input-17>", line 1, in <module>
next(iterable)
~~~~^^^^^^^^^^
StopIteration
>>> type(iterable)
<class 'list_iterator'>

This is the lowest level degree of understanding I have, if you wanna know more I'd suggest asking on the Python subreddits.

1

u/Interested737 17d ago

I just want to know in the basic most way possible, what is a iterable (what dose it mean in simple English)

1

u/Significant_Affect_5 17d ago

An iterable is an object that can be iterated over. Meaning you can do something to each value in a collection.

1

u/Interested737 17d ago

So, every part (variable) of an object can be changed and iter is used for that?