0

Replacing the value in the list

List

a=[5,6,7,5,8,7]

replace 7 with 3

required output

[5,6,3,5,8,7]

Condition?

With out slice?

  • In this link if list have 2 or more value of same number all numbers are replaced but i want to change only specific location value? – Ashok Kumar Reddy Kummetha Aug 01 '19 at 17:26
  • Just use the index.... Thats primarily what `[ ]` is for. `my_list[2] = 3`. If you have trouble with this you should really just follow a tutorial on python. (Technically this is a standard feature for almost all core languages) – Error - Syntactical Remorse Aug 01 '19 at 17:41
  • @Ashokkumarreddy What you indicate in your comment does not match the example you provide in your question – eyllanesc Aug 01 '19 at 17:45
  • @Ashokkumarreddy From your edition I understand that if there are several items with the same value (in your example "7") you only want to change the first value. Am I correct? If so, then use: `for n, i in enumerate(a):` `if i == 7:` `a[n] = 3` `break` – eyllanesc Aug 02 '19 at 04:17
  • possible duplicate: https://stackoverflow.com/questions/2582138/finding-and-replacing-elements-in-a-list – foobar Apr 09 '20 at 13:04

1 Answers1

1

You can use a list comprehension:

[3 if x==7 else x for x in a]
Carsten
  • 2,765
  • 1
  • 13
  • 28