views:

253

answers:

5

Hey

I have to search through a list and replace all occurrences of one element with another. I know I have to first find the index of all the elements, and then replace them, but my attempts in code are getting me nowhere. Any suggestions?

+8  A: 

Try using a list comprehension and the ternary operator.

>>> a=[1,2,3,1,3,2,1,1]
>>> [4 if x==1 else x for x in a]
[4, 2, 3, 4, 3, 2, 4, 4]
outis
+1  A: 
>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> item_to_replace = 1
>>> replacement_value = 6
>>> indices_to_replace = [i for i,x in enumerate(a) if x==item_to_replace]
>>> indices_to_replace
[0, 5, 10]
>>> for i in indices_to_replace:
...     a[i] = replacement_value
... 
>>> a
[6, 2, 3, 4, 5, 6, 2, 3, 4, 5, 6]
>>> 
gnibbler
+1  A: 
>>> a=[1,2,3,4,5,1,2,3,4,5,1]
>>> for n,i in enumerate(a):
...   if i==1:
...      a[n]=10
...
>>> a
[10, 2, 3, 4, 5, 10, 2, 3, 4, 5, 10]
ghostdog74
+1  A: 

List comprehension works well--and looping through with enumerate can save you some memory (b/c the operation's essentially be doing in place).

There's also functional programming...see usage of map:

    >>> a = [1,2,3,2,3,4,3,5,6,6,5,4,5,4,3,4,3,2,1]
    >>> map(lambda x:x if x!= 4 else 'sss',a)
    [1, 2, 3, 2, 3, 'sss', 3, 5, 6, 6, 5, 'sss', 5, 'sss', 3, 'sss', 3, 2, 1]
damzam
+1. It's too bad `lambda` and `map` are considered unpythonic.
outis
I'm not sure that lambda or map is inherently unpythonic, but I'd agree that a list comprehension is cleaner and more readable than using the two of them in conjunction.
damzam
@damzam: I don't consider them unpythonic myself, but many do, including Guido van Rossum (http://www.artima.com/weblogs/viewpost.jsp?thread=98196). It's one of those sectarian things.
outis
A: 

I apologize but this sounds like a homework problem. We have a policy on these: http://meta.stackoverflow.com/questions/10811/homework-on-stackoverflow

However, what I would suggest is that you post the code you tried that failed and show why you think it failed and/or where the problem is, and people will be more willing to help you out.

For example, if you've barely begun your assignment or looked at Python and its data structures, you'll have a tough time with all the suggestions posted here so far.

wescpy