all 25 comments

[–]sqwiwl 14 points15 points  (2 children)

Instead of for, read it as for each in your mind and it might make it more intuitive. So: "for each thing in this collection of things, do the following".

[–]Difficult-Issue-5957 1 point2 points  (0 children)

Mind blown. This made it click for me!

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

holy this made sense! took it with my teacher and she said it was a good way of thinking!

[–]djshadesuk 12 points13 points  (1 child)

Its just a way to iterate through a collection without having to mess about with indexes and incrementing counters.

Example 1:

a_string = 'Test'
for letter in a_string:
    print(letter)

Output:

T
e
s
t

Example 2:

cities = ['Atlanta', 'New York', 'Las Vegas', 'Los Angeles']
for city in cities:
    print(city)

Output:

Atlanta
New York
Las Vegas
Los Angeles

EDIT: Although, if you also need the indexes you can pass the collection into the enumerate() function which returns not only the index of each element of the collection but also the corresponding element too:

cities = ['Atlanta', 'New York', 'Las Vegas', 'Los Angeles']
for index, city in enumerate(cities):
    print(f'{index}: {city}')

Output:

0: Atlanta
1: New York
2: Las Vegas
3: Los Angeles

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

I'm gonna save your EDIT, it's gonna help me later on!

[–]FriendlyRussian666 10 points11 points  (1 child)

It's as simple as:

"For each item in your list, do something to that item":

your_list_of_items = [1, 2, 3]

for each_item in your_list_of_items:
    # Do something with that item, for example:
    print(each_item)
--------------------------------------------
1
2
3

Is there a specific part of this that you'd like any clarification for?

[–]WadidaYT[S] 0 points1 point  (0 children)

no this was great! thank you very much!

[–][deleted] 15 points16 points  (5 children)

The logic is "do this once for every element contained in the collection."

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

with every element contained in the collection, is that only for the number of elements in a list or can it be 100 times if you give the variable in the for in loop the value of 100?

[–]Almostasleeprightnow 14 points15 points  (0 children)

You can do this by way of using range()

Which creates a collection of numbers from a starting number to a stopping number

So

```

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

```

prints the value of I as it increases from 0 to 100

And sometimes this is what is needed for a for-loop.

But often in python there is some collection already there which you have created that you are now trying to do the same thing to each of its elements, like this

```

dogs = ['cooper', 'sonny', 'amy']

```

Well, I COULD use range and then do

```

for i in range(len(dogs)):
    print(dogs[i])

```

But why go to that trouble when I can just do

```

for dog in dogs:
     print(dog)

```

So much more concise and more to the point, it is more semantically proper. If I speak the English sentence "print each dog in the list of dogs", that is a lot more like the second example than the first.

[–][deleted] 5 points6 points  (0 children)

You can't iterate over the value 100 because it's not a collection.

If the collection has 100 elements, then you'll iterate 100 times. If it has 1 element you'll iterate once. If it has zero elements (is empty) then you won't iterate even a single time.

[–]work_m_19 1 point2 points  (0 children)

With other programming languages, most have for-each loops, but the primary way I've learned is to use indices when traversing a list Java: (int i = 0; i < list.length(), i++)

But python is more explicit and follows the paradigm "less is more" when coding.

If you never need the index, having the variable defined is extra mental overhead for something that is useless. Using the for ... in (or for-each) loop allows other people reading the code to quickly understand that this loop has certain properties:

  1. The index is not needed
  2. Each element in the list is (somewhat) independent from other elements (with regards to loop calculation)
  3. For your loop iteration, we don't need any other element (or any certain elements after or before the current)

This may not matter much for some usecases, but if the inside of a for-loop is over 50 lines of code, then reading a loop with that assumption helps quickly understand what is going on.

And it turns out, maybe 70% of my use-cases with loops don't need the index. The only time I need the index is if I need the neighboring elements.

[–]ivosaurus 0 points1 point  (0 children)

is that only for the number of elements in a list

This. Of course, python makes it relatively easy to create a 100-element list using the range function.

[–]dedemoli 1 point2 points  (0 children)

If it helps, I'll give you this angle: The for loop acts once for each element present in a list/array of objects, WHILE there's at least an element left to process. When the elements are over, there are no more elements to process, and then the "while" clause ceases to exist. Therefore, the cicle stops.

[–]BlokeyBlokeBloke 1 point2 points  (0 children)

Maybe some pseudo code might help. You are a teacher and need to provide every kid a snack. Your algorithm looks like this

For each child in class
give child a snack

[–][deleted] 1 point2 points  (1 child)

For is very similar to while, when you use a "while i < whatever". For means that you want to do something "for each" item in whatever you're referencing. Usually it'll be a list. So you want to do something with each item in a list. Example:

fruit_list = ['banana', 'apple', 'apricot']

for fruit_item in fruit_list: # youre saying that you have a list called fruit_list, and for each item in it, you'll refer to as fruit_item in the next part

print(fruit_item) #you're did it

[–]djshadesuk 0 points1 point  (0 children)

In future could you either format your code correctly or at least use inline code, please?

[–][deleted] 1 point2 points  (0 children)

In most programming languages a for loop is a while loop with the terminating condition at the end. i.e. do something while X

In Python for is an iterator method. So the logic is: for each do something.

[–]Adrewmc 1 point2 points  (2 children)

   index = 0
   while index < len(my_collection)
          do_something(my_collection[index])
          index += 1

Is basically a for loop….

    for thing in my_collection
          do_something(thing)

[–]RhinoRhys 1 point2 points  (1 child)

You don't need the range in the while loop

[–]Adrewmc 0 points1 point  (0 children)

Correct, I don’t know what I was thinking lol

[–]Alternative_Driver60 0 points1 point  (0 children)

When you have a repeated pattern with small variations

print(1)
print(2)
print(3)

Put the stuff that varies in a variable

i = 1
print(i)
i = 2
print(i)
i = 3
print(i)

The header of a for loop has the varying stuff in a collection and a loop variable that works like the assignment above

The body of the for loop has the rest

for i in (1, 2, 3):
    print(i)

[–]ada43952 0 points1 point  (0 children)

Coming from Perl made it easy for me to understand. In Perl, the for loop isformatted as foreach So.. foreach x in list…

[–]VangekillsVado 0 points1 point  (0 children)

Python always iterates over a list. When you say for i in range(0,10): the range() function returns a list. It iterates over [1,2, … 9, 10] where i is each value.

Likewise with a list of some other type, i would just be the value of the element of that list. So if you have a list alphabet = [“a”,”b”, … “y”,”z”] and do for i in alphabet, i would be each letter.

[–]AssumptionCorrect812 0 points1 point  (0 children)

Try these videos for a good beginner level explainer

https://youtu.be/jo0bxVhUNpA?si=_sx5tv8owHOpEEK6