-3

I am trying to replace the value 11 with the value of 1.

What am I doing wrong?

enter image description here

I want it to be:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
Sylvester Kruin
  • 2,114
  • 3
  • 8
  • 36

4 Answers4

1

You could do this with a list comprehension:

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
[1 if i==11 else i for i in cards]

Output:

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

In your exampe i is an item in list, not an index:

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

for i, val in enumerate(cards):
    if val == 11:
        cards[i] = 1


print(cards)
var211
  • 577
  • 5
  • 10
-1
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11]
i = 0
while i < len(my_list):
    if my_list[i] == 11:
        my_list[i] = 1
    i += 1
MATOS
  • 146
  • 7
  • this is not correct, it should be ```for i in range(len(list)):``` or ```for i, _ in enumerate(list):``` also, you shouldn't overwrite the builtin python ```list``` – Nin17 May 02 '22 at 20:43
  • Don't use `list` as a name for a variable. You're overwriting the built-in [`list`](https://docs.python.org/3/library/functions.html#func-list). And why do you use `else` if you just continue? – Matthias May 02 '22 at 20:43
  • else was just to show what happens if that isn't true, the listname was quick thinking – MATOS May 02 '22 at 20:47
  • @Nin17 There is nothing wrong with ```for i in my_list``` it all works just the same – MATOS May 02 '22 at 20:48
  • @MATOS no it doesn't try it. Put ```print(list)``` after that and you get ```[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 11]``` note the 11 is still there. If you change the values you can easily get an ```IndexError: list index out of range``` error which you're only avoiding because ```len(list)>max(list)``` – Nin17 May 02 '22 at 20:48
  • yes very sorry about that, forgot that it skipped those, I added a sample while loop for another example of choice – MATOS May 02 '22 at 20:58
  • well apart from it changing 11 to 10 instead of 1 it works now – Nin17 May 02 '22 at 21:31
  • Still not a good answer, but at least working. – Matthias May 03 '22 at 07:08