-1

i have a list say

a= [1,2,3,4,5,7,1,2,3,1]

i want to replace 1 with 10 in a.
so new list should be

[10,2,3,4,5,7,10,2,3,10]
Nick_1405
  • 23
  • 3

7 Answers7

2

Most pythonic way to do this is using a list comprehension:

a = [1, 2, 3, 4, 5, 7, 1, 2, 3, 1, ]
a = [10 if number == 1 else number for number in a]

If you have to replace more than one number you can use a mapping:

a = [1, 2, 3, 4, 5, 7, 1, 2, 3, 1, ]
mapping = {
# old: new
  1: 10,
  2: 20,
}
a = [mapping.get(number, number) for number in a]

That last line will search for the number in your mapping, if found it will use the replacement, if not the original value.

Hrabal
  • 2,403
  • 2
  • 20
  • 30
1

You can do this:

a= [1,2,3,4,5,7,1,2,3,1]
for i,v in enumerate(a):
    if v == 1:
        a[i] = 10
print(a)

Output:

[10,2,3,4,5,7,10,2,3,10]
Vaibhav Jadhav
  • 2,020
  • 1
  • 7
  • 20
0

Using list comprehension:

a = [1,2,3,4,5,7,1,2,3,1]
b = [10 if v == 1 else v for v in a]
print(b)

Output:

[10, 2, 3, 4, 5, 7, 10, 2, 3, 10]
Gábor Fekete
  • 1,343
  • 8
  • 16
0

In addition to @Vaibhav answer, You can also build a new list with a list comprehension:

a_modified = [10 if x == 1 else x for x in a]
oprezyzer
  • 101
  • 11
0

You can do any list editing fairly easily with list comprehensions. In this case, you can do:

a = [x if x!=1 else 10 for x in a]
SatoriChi
  • 31
  • 2
0

If you are reading your list from a dataset. You can deal with the data frame directly as follows.

for i in range(len(df)):
    if(df.loc[i,'column'] == 1):
        df.at[i, 'column'] = 10
        Continue;
Fatemeh
  • 45
  • 8
0

replace 1 with 10

a = [1,2,3,4,5,7,1,2,3,1]
a1_data = []
for i in a:
    if i == 1:
        i = 10
        a1_data.append(i)
    else:
        a1_data.append(i)
print(a1_data)
vijju
  • 21
  • 2