AlexEfremo
AlexEfremo

Reputation: 813

Manually replace elements in a list

Example:

a = [1,2,3,2,4,2,5]
for key in a:
    if key == 2:
        key = 10
print key

Result: [1,10,3,10,4,10,5]

I need Python to "ask" manually which of the elements to replace.

Upvotes: 1

Views: 119

Answers (2)

TerryA
TerryA

Reputation: 59974

You're looking for enumerate():

for indx, ele in enumerate(a):
    if ele == 2:
        a[indx] = 10
print a

Prints:

[1, 10, 3, 10, 4, 10, 5]

If the value you want to change is an input, then simply just do:

change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())
for indx, _ in enumerate(a):
    if change[0] == 2:
        a[indx] = change[1]

Or as a list comprehension (If you like this solution upvote Ashwini's :)):

change = map(int, raw_input("What number do you want to change in the list? And what number should it be? Separate both numbers with a space ").split())
[change[1] if x == change[0] else x for x in a]

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

>>> a = [1,2,3,2,4,2,5]
>>> a[:] = [10 if x==2 else x for x in a]
>>> a
[1, 10, 3, 10, 4, 10, 5]

If you want to replace multiple items then consider using a dict:

>>> dic = {2 : 10}
>>> a[:] = [dic.get(x,x) for x in a]
>>> a
[1, 10, 3, 10, 4, 10, 5]

Upvotes: 7

Related Questions