is there a better way...

Gustavo Niemeyer niemeyer at conectiva.com
Fri May 10 16:00:36 EDT 2002


> to loop over a list and replace an element based on its value than:
> 
> x = [1,2,3,4,5,6,7,8,9]
> y = len(x)
> z = 0
> while z < y:
>     element = x[z]
>     if element == 5: x[z] = '678'
>     z = z +1

Sure!

>>> x = [1,2,3,4,5,6,7,8,9]
>>> y = 5
>>> z = '678'
>>> [b for a in x for b in [[a, z][a==y]]]
[1, 2, 3, 4, '678', 6, 7, 8, 9]

;-))

-- 
Gustavo Niemeyer

[ 2AAC 7928 0FBF 0299 5EB5  60E2 2253 B29A 6664 3A0C ]





More information about the Python-list mailing list