The Student Room Group

for loop in python

what does this for loop below actually do?

for i, x in enumerate(self.list):
.....
(edited 2 years ago)
i is the "index" for the list, x is the actual variable in the list

For example

for i, x in enumerate([a,b,c,d]):
print(i, x)

would print

0 a
1 b
2 c
3 d
Original post by Callicious
i is the "index" for the list, x is the actual variable in the list

For example

for i, x in enumerate([a,b,c,d]):
print(i, x)

would print

0 a
1 b
2 c
3 d

is there a way of producing the same outcome without the use of enumerate?
(edited 2 years ago)
Original post by Carrying a torch
is there a way of producing the same outcome without the use of enumerate?

There's always a way, but why would you want to?
Original post by Callicious
There's always a way, but why would you want to?

It might better help me understand because I have not come across the use of 'enumerate' before, is it like range or len?
Original post by Carrying a torch
It might better help me understand because I have not come across the use of 'enumerate' before, is it like range or len?

See https://towardsdatascience.com/python-enumerate-built-in-function-acccf988d096

Personally I find it invaluable when working with loops- it's useful for calling to lists separate from the one you're iterating through that may have the same indices as the one you're iterating through.
Original post by Callicious
See https://towardsdatascience.com/python-enumerate-built-in-function-acccf988d096

Personally I find it invaluable when working with loops- it's useful for calling to lists separate from the one you're iterating through that may have the same indices as the one you're iterating through.

Still not sure how the same could be achieved without enumerate but I think that clarifies a lot
Original post by Carrying a torch
Still not sure how the same could be achieved without enumerate but I think that clarifies a lot

I mean, before I learned about enumerate() and zip() I usually just did something like

list = example_list
indices = np.arange(0, len(list), 1)
for num in indices:
x_num = list[num]

Alternatively just use

for num in range(len(indices)):
etc etc

You've got options aside from enumerate- it's just way more convenient and easier.
Original post by Carrying a torch
is there a way of producing the same outcome without the use of enumerate?

enumerate() is a function... it behaves like any other function you've come across. Its name is actually really descriptive of what it does; it enumerates the elements within an iterable (e.g a list, a tuple, a string). This is the code for enumerate(), it's really simple:

def enumerate(sequence, start=0):
n = start
for elem in sequence:
yield n, elem
n += 1


When you use enumerate() in a for loop, it removes the need for having to code your own counter. See for youself what it does by entering enumerate(["a", "b", "c", "d"]) into IDLE Shell.
(edited 2 years ago)

Quick Reply

Latest

Trending

Trending