For loops

Hey everyone :wave:

I am having some troubles while learning python loops.
I’ve seen in some scenarios that people use the following syntax:

for i in range(len(list)): #loop 1
.
.
.
And sometimes I also see this:
for i in list: #loop 2
.
.
.

How could I know which one to use?
What are the differences?

The difference is mostly readability; generally in Python the second option is preferred when possible and it simply steps through item by item in a sequence. This is generally considered easier to read and maintain.

mylist = [1, 2, 3]
for element in mylist:
    print(f'{element = }')

You can do this over any iterable object (without going into too much detail this roughly all the sequence data types: lists, tuples, sets, dictionary keys etc. and a few others). Just be aware that some are ordered and others aren’t.

Sometimes however indexing values becomes necessary. If so, the next best option is the in-built enumerate function. A very quick example-

mylist = [1, 2, 3]
for index, element in enumerate(mylist):
    print(f'In mylist at {index = }, {element = }')

If neither of those suit then you may need to use range but it should probably be your last choice.

2 Likes

Main difference is if you need to grab the index versus the value at that iteration.

Loop one will allow you to get list[i] an do things with that index like list[i+1].

Second loop is just a simplified version of the first one that just grabs the value of that iteration without the ability to do something with it. If we just need the value the second loop is likely what you need. If you need to do something with the value at that index like math then you use the first loop.

1 Like

Thank you very much mate!!

Perfect, thank you!!