0

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

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, I can't believe how long it took me to find this answer.
3
b=["hi","hello","howdy"]
for count,i in enumerate(b):
    print count

Comments

1

you could always do this:

b=["hi","hello","howdy"]
for i in range(len(b)):
    print i

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.