python modify item in list, save back in list

Question:

I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index

I’m having difficulty getting an item back into the same index

for item in list:
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[item] = item
        print item

now I get an error

TypeError: list indices must be integers, not str

due to this line list[item] = item

which makes sense! but I do not know how to put the item back into the list at that same index using python

what is the syntax for this? Ideally the for loop can keep track of the index I am currently at

Asked By: CQM

||

Answers:

You could do this:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item
Answered By: Cat Plus Plus

You need to use the enumerate function: python docs

for place, item in enumerate(list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item

Also, it’s a bad idea to use the word list as a variable, due to it being a reserved word in python.

Since you had problems with enumerate, an alternative from the itertools library:

for place, item in itertools.zip(itertools.count(0), list):
    if "foo" in item:
        item = replace_all(item, replaceDictionary)
        list[place] = item
        print item
Answered By: Spencer Rathbun

A common idiom to change every element of a list looks like this:

for i in range(len(L)):
    item = L[i]
    # ... compute some result based on item ...
    L[i] = result

This can be rewritten using enumerate() as:

for i, item in enumerate(L):
    # ... compute some result based on item ...
    L[i] = result

See enumerate.

Answered By: Ershadul

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
    if 'foo' in item:
        ListOfStrings[idx] = "bar"
Answered By: Mattman85208
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.