Pierre Pierre - 2 years ago 68
Python Question

How to change element in list from information in another list

I want to create lists (named 'card') of two elements : 'NUMBER' and a number from the list 'numbers'. There will be as many cards as there are numbers in the list 'numbers'.
Why do I get cards with the same number using that code ?

numbers = [1,3,5]
for i in range(len(numbers)):

What I get : [['NUMBER', 5], ['NUMBER', 5], ['NUMBER', 5]]

What I want : [['NUMBER', 1], ['NUMBER', 3], ['NUMBER', 5]]

Answer Source

You have already excellent answers that solve your immediate problem (I suggest that you try to understand the mechanism of list comprehension, introduced in Mr Roseman answer, because it's extra handy in too many situations) but maybe you would like to understand why you had that strange result.

You had that strange result because you can change the contents of a list..

Eh? follow me, when you type at the prompt of the interpreter

>>> ['NUMBER', '']
['NUMBER', '']

you are creating a list, that is lost immediately (it's not exact, but) — if you make an assignment

>>> card = ['NUMBER', '']

you have created a list (rhs of =) and assigned a name (card, the lhs of =) to this list.

Now you use a for loop, and

  1. All_cards.append(card) doesn't mean that you are appending a copy of your list, you are appending (three times) the same list.
  2. All_cards[i][1]=numbers[i] means that you're modifying, in all three passes in the loop, the same list.
  3. When you print(All_cards) you see that all the three elements are the same, and that the second element of the inner list is the last numeric value that you have used inside the loop...

May I add that this is, sort of, a rite of passage for every Python programmer? Bon voyage

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download