Timmy
Timmy

Reputation: 81

How can I iterate over a list of strings with ints in python?

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

Upvotes: 0

Views: 103

Answers (3)

impactblu
impactblu

Reputation: 107

you could always do this:

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

Upvotes: 1

Foo Bar User
Foo Bar User

Reputation: 2491

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

Upvotes: 3

Blender
Blender

Reputation: 298166

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]

Upvotes: 4

Related Questions