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]
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.
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]
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]
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]
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]
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;
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)