-1

How do I change a number in a list without knowing the position the number is in? For example, if I had:

numbers = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

Say I wanted to change the number 11 to 1 and I do not know that 11 is in position 0.

I do not want to do something like,

if 11 in numbers:
    number[11] = 1

because this would change number 10 to 1. So, no matter where the 11 is in the list, it will replace it with a 1.

The code above is basically checking if there is an 11 in the list and if there is, it will replace it with 1.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
owen_coding
  • 3
  • 1
  • 3
  • `number[11]` is the 12th (due to 0-based indexing) element in the list, not whichever one (if any) happens to have the value `11`. – jonrsharpe May 15 '21 at 13:33
  • Yes, I am aware of this. I am trying to find out how i would get the value 11 changed to 1. No matter what position it is in. – owen_coding May 15 '21 at 13:37
  • 1
    Then are you asking "how do I find the index of a value in a list?" and, if so, have you tried any research to figure that out? – jonrsharpe May 15 '21 at 13:38
  • Originally, the thought of finding the index of the value did not occur to me. I did do research, but I was searching with the wrong question. Though I am grateful someone gave the answer that I was looking for. – owen_coding May 15 '21 at 13:48

3 Answers3

1

Iterate through the indexes of the list:

numbers = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
for i in range(len(numbers)):
    if numbers[i] == 11:
        numbers[i] = 1

print(numbers)
#[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
pakpe
  • 5,391
  • 2
  • 8
  • 23
  • @OlvinRoght Yes, you can do this a thousand different ways. – pakpe May 15 '21 at 13:42
  • There are a thousand ways to do this, but [this answer to the duplicate](https://stackoverflow.com/a/59478892/3216427) seems to be the fastest solution, with [benchmarks in this other answer to the duplicate](https://stackoverflow.com/a/59826095/3216427). – joanis May 15 '21 at 15:22
0
numbers = [x if x is not 11 else 1 for x in numbers]
Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
0

Use index method of list objects.

numbers[numbers.index(11)] = 1

It will fail if 11 is not in numbers. It will replace only the first occurrence.

Jon Franco
  • 143
  • 6