Sharpowski
Sharpowski

Reputation: 627

TypeError: list indices must be integers, not str - iterating list

I would like to do something like this:

def create(stuff):
    someString = ''
    for i in stuff:
        someString += stuff[i]
        print(someString)

create(['Foo', 'Bar'])  
# -> FooBar

I tried to change it to string like this:

someString += str(stuff[i])

but still get error.

Upvotes: 0

Views: 2142

Answers (3)

s16h
s16h

Reputation: 4855

The problem is the way you are accessing the elements in stuff. The following code does it correctly and the explanation follows:

def create(stuff):
    someString = ''
    for element in stuff:
        someString += element

    print(someString)

When you use Python's for statement, unlike C/C++/Java etc. for loops, you don't work with indexes. So, when iterating over a list (or any other iterable) like for i in ['a', 'b', 'c'], the value of i will be the actual value in the iterable. For example, in the first iteration, i will be 'a' and not 0 (as in the 0th index)

Upvotes: 3

A.J. Uppal
A.J. Uppal

Reputation: 19264

Your problem is the stuff[i]. i is not an integer, it is a string.

>>> x = ['hi', 'bye']
>>> for k in x:
...        print k
... 
hi
bye
>>>

Instead, change it to the following:

def create(stuff):
    someString = ''
    for i in range(len(stuff)):
        someString += stuff[i]
        print(someString)

Or:

def create(stuff):
    someString = ''
    for i in stuff:
        someString += i
        print(someString)

The first example uses indices, and the second uses a plain for loop.

Upvotes: 1

Bryan
Bryan

Reputation: 2088

When you use a for in loop, i will be equal to the object itself, not the index. In Python, if you wanted to iterate by index, you could for example use range:

someString = ''
for i in range(len(stuff)):
    someString += stuff[i]
    print(someString)

Upvotes: 3

Related Questions