I really wanted to know how to use “enumerate” and what’s the difference with "for i in range(len(something))?
Sometimes the caption tells me to iterate over something. I normally just use "for i in range(len(something)), but in the level “Sleepwalkers” I think you have to use enumerate. Can someone please tell me how to use it and the difference? Thanks so much !
# example: something = ["something", "test", "list"]
a = range(len(something))
b = enumerate(something)
print(list(a)) # ==> [0, 1, 2]
print(list(b)) # ==> [(0, 'something'), (1, 'test'), (2, 'list')]
It’s the difference. And you can use as this:
for i in range(len(something)):
item = something[i]
print(i, ":", item)
for i, item in enumerate(something):
print(i, ":", item)
And output.
0 : something
1 : test
2 : list
enumerate
can help writing shorter code, but there are not an essential difference.
3 Likes
This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.