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)):
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
All_cards.append(card)doesn't mean that you are appending a copy of your list, you are appending (three times) the same list.
All_cards[i]=numbers[i]means that you're modifying, in all three passes in the loop, the same list.
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