I'm new to programming with python and programming in general and got stuck wit the following problem:
b=["hi","hello","howdy"]
for i in b:
print i
#This code outputs:
hi
hello
howdy
How can I make it so the iterating variable is an int so it works the following way?
b=["hi","hello","howdy"]
for i in b:
print i
#I want it to output:
0
1
2
The Pythonic way would be with enumerate()
:
for index, item in enumerate(b):
print index, item
There's also range(len(b))
, but you almost always will retrieve item
in the loop body, so enumerate()
is the better choice most of the time:
for index in range(len(b)):
print index, b[index]
b=["hi","hello","howdy"]
for count,i in enumerate(b):
print count
you could always do this:
b=["hi","hello","howdy"]
for i in range(len(b)):
print i
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.