0

what is enumerate in python?

5th Nov 2018, 7:47 PM
kokito
5 Antworten
+ 3
I can't give you a good description of enumerate, but here's a solid example. Langs = ['JS', 'PHP', 'C#', 'C++'] enum = enumerate(langs) for [index, item] in enum: print(index, item) Output ====== 0 JS 1 PHP 2 C# 3 C++ Try giving it your own definition
5th Nov 2018, 9:00 PM
Dlite
Dlite - avatar
+ 2
Mbrustler thanks
5th Nov 2018, 10:14 PM
Dlite
Dlite - avatar
+ 1
#I think the best explanatoin would be to try it out so try A = "hello" for i in enumerate(A): print(i) # in this example every char in a becomes a number from range(len(A)) assigned and will be hmm i would say transformed into a tuple of the char and the number
5th Nov 2018, 8:19 PM
Mbrustler
Mbrustler - avatar
+ 1
D'lite shouldnt it be for [index,item] in enum: ?
5th Nov 2018, 9:04 PM
Mbrustler
Mbrustler - avatar
0
There's the 'C-ish' way to loop through an iterator: for i in range(len(mylist)): print(mylist[i]) Then the more simple way: for item in mylist: print(item) There are cases when you want to do both in your loop, access the item AND have the index. Then you can use for i, item in enumerate(mylist): ...
5th Nov 2018, 11:02 PM
HonFu
HonFu - avatar