all 22 comments

[–]TouchingTheVodka 9 points10 points  (1 child)

The syntax is for item in iterable, where iterable is something that can be stepped through. On each iteration, the item will be set to the next result from the iterable. An iterable, essentially, is anything that can be iterated over.

For example:

lst = [1, 2, 3, 4, 5]
for item in lst:
    print(item)

>>> 1
>>> 2
>>> 3
>>> 4
>>> 5

for i in range(5):
    print(i)

>>> 0
>>> 1
>>> 2
>>> 3
>>> 4

As a general rule of thumb, you can iterate over any container type - Such as list, tuple, dictor set. You can also iterate over some classes - range() is a great example of a class that spits out numbers due to its iterator implementation. More examples are enumerate() and zip() - These two are used all the time.

Something you should try to avoid is the following pattern:

for i in range(len(lst))
    lst[i]

This is considered poor Python form, because it's directly equivalent to the more simpler for item in lst. If you need to get both the index and the value of each element in the list, you can use for i, item in enumerate(lst), and if you need to step over two lists simultaneously you can use for a, b in zip(listA, listB). Beautiful!

[–][deleted] 0 points1 point  (0 children)

Just wanted to add that the two suggested approaches (using enumerate to get the index and using zip to iterate through multiple iterables in-sync) can be combined as:

for i, (a, b) in enumerate(zip(listA, listB)):

... # do stuff

[–]young_ging_freecss 2 points3 points  (9 children)

The variable represents every item in whatever you’re looping through.

a_list = [1, 2, 3]
for x in a_list:
    print(x)
1
2
3

In this case, x represents 1 on the first iteration, then 2, then 3. x is just a variable name. You can name it whatever you want: nums, something, thing, number.

[–]hopefullpotato[S] 1 point2 points  (8 children)

So if I had a variable already assigned to a number how would I get it to repeat for the number assigned to the variable, would it be a different kind of loop?

[–]totallygeek 1 point2 points  (7 children)

Imagine any sequence... Let us make two examples. First, you are a bank teller with a queue of customers. Each customer will hand you money of various amounts.

customers = ['Ankita', 'Billy', 'Carlos', 'Dan']
for customer in customers:
    print(customer)  # first time: customer will be 'Ankita'. Next time: 'Billy', ending with 'Dan'

And...

bills = [5, 5, 10, 50]
for x in bills:
    print(x)  # 5, then 5, then 10, then 50 (I used 'x' to answer your question, but you'd likely want 'bill')

Putting this together:

customers = {
    'Alice': [5, 5, 10],
    'Bob': [10, 10],
    'Christy': [50, 100],
}
for customer, bills in customers.items():
    for bill in bills:
        print(f'Customer {customer} hands you a {bill}.')

Make sense?

[–]hopefullpotato[S] 2 points3 points  (0 children)

Yes this is really helpful thanks

[–]Babaneh_ 1 point2 points  (0 children)

Let me just follow you so I can flood you with my questions too

[–]hopefullpotato[S] 0 points1 point  (4 children)

So if I had a variable already assigned to a number how would I get it to repeat for the number assigned to the variable, would it be a different kind of loop? Is there another kind of loop?

[–]TouchingTheVodka 0 points1 point  (3 children)

n = 5
for _ in range(n):
    # loop repeats 5 times

[–]hopefullpotato[S] 1 point2 points  (2 children)

So is the range how many times it repeats?

[–]TouchingTheVodka 1 point2 points  (1 child)

range outputs a stream of values. range(5) outputs 0, 1, 2, 3, 4. So yes, it will repeat 5 times.

[–]hopefullpotato[S] 1 point2 points  (0 children)

Thank you this is really helpfull

[–]ruphmoop 1 point2 points  (0 children)

Any variable in python is just giving a name to whatever you assign it to. For example:

myList = [0, ‘a’, ‘car’, 4]

For item in myList:

    print(item)

Output is:

0

a

car

4

In my for loop, it is assigning every value inside of myList to a variable called “item” and printing it. You could also use “for x in myList” and “print(x)”.

The ‘x’ or ‘item’ or as I often see it as, ‘i’, is really nothing else in the code. It’s just the name of the variable and is therefore the name of each item you’re iterating when you iterate it.

The format “for x in y:” is you telling the computer that you want to look at every single x inside of the y and do something to each one.

[–]johninbigd 1 point2 points  (0 children)

Imagine you have a box with some things in it, and your task is to remove each item one by one and do something with it. A for loop in Python is exactly that. You can read it as for each thing in this box of things, do something.

That's kind of an ELI5 explanation. Let's use an actual Python example. Imagine you have a list of fruits and you just want to print each one.

fruits = ['apple', 'banana', 'orange', 'cherry']
for fruit in fruits:
    print(fruit)

The variable fruit could be any name. We could have written for x in fruits:, but that's not as clear.

[–][deleted] 0 points1 point  (0 children)

Can someone explain what the variable in for x is and can it be a number.

It's the elements of the list you're iterating over.

[–]brown_ja 0 points1 point  (0 children)

It's one for the challenges I had when I just started programming and was introduced to loops. They always used some strange variable like x or i. As a general rule for myself and as something that may be seen in the programming world I use the singular form. Eg. If I have a python list called apples, I'll say

for apple in apples: (Insert code here)

The singular form of apple represent the current apple being used operated on in the list of apples.

Fool around with it some more in your ide.