37

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

CQM
  • 42,592
  • 75
  • 224
  • 366
  • 1
    Why do you have to do it in place in the list? My initial reaction was to use a list comprehension: res = [ replace_all(item,replaceDictionary) for item in list if 'foo' in item ] – krs1 May 25 '11 at 20:22
  • thats pretty crafty, but how is that any different than this? – CQM May 25 '11 at 20:26
  • 1
    The only issue i can see is that you're attempting to reference a list item by using the item itself not the index of the item. Looks fine other than that. Also, you're modifying the list item before referencing it. Could be an issue for dictionaries. – krs1 May 26 '11 at 02:38
  • 2
    General question about the above, is replace_all deprecated or something? Or am I missing that it's a custom function that's not defined in the code. – techcyclist Mar 05 '19 at 23:55
  • Also here: https://stackoverflow.com/questions/4081217/how-to-modify-list-entries-during-for-loop/4082739 – Jeyekomon Nov 04 '21 at 13:29

4 Answers4

58

You could do this:

for idx, item in enumerate(list):
   if 'foo' in item:
       item = replace_all(...)
       list[idx] = item
Cat Plus Plus
  • 125,936
  • 27
  • 200
  • 224
  • `ValueError: too many values to unpack` , I have been suspecting that I have been running out of space for my lists, is there a way to pre-manage how much space to address to dive further into the list? (might be a new question) – CQM May 25 '11 at 20:11
  • 4
    @RD.: You sure you've used enumerate? – Cat Plus Plus May 25 '11 at 20:12
  • ah, did not notice that in thise post. This seems to have worked. Although I run into the memory space issue again when I try to join that into a string `listString = ''.join(list)` , for some reason it decides to print out how far it goes to the console, and does not complete the rest of the program – CQM May 25 '11 at 20:18
  • Got this with Python 3: NameError: name 'replace_all' is not defined – Mattman85208 Aug 29 '19 at 13:42
8

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
Spencer Rathbun
  • 14,510
  • 6
  • 54
  • 73
6

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.

Chamath
  • 2,016
  • 2
  • 21
  • 30
Ershadul
  • 61
  • 1
  • 4
1

For Python 3:

ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
    if 'foo' in item:
        ListOfStrings[idx] = "bar"
edesz
  • 11,756
  • 22
  • 75
  • 123
Mattman85208
  • 1,858
  • 2
  • 29
  • 51