I have a list called deck with 16 items in it:
deck = range(0,8)*2
I need to create a list that has the same number of entries as the deck list, but initially, they're all set to False
Say the name of the new list is new_list
How do I create this list without typing False 16 times? When I try this, I get index out of range error.
deck = range(0,8)*2
new_list = []
for card in deck:
new_list[card] = False
Thanks
You can repeat a list multiple times by multiplying it. For example, this will solve your problem:
>>> [False] * 16
[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
You can also do this with multiple elements in a list, like so:
>>> [1, 2] * 5
[1, 2, 1, 2, 1, 2, 1, 2, 1, 2]
If you wanted to ensure that the list would expand as you changed the size of the deck, you could multiply by the length, like this:
deck = range(0, 8) * 2
falses = [False] * len(deck)
You can read the documentation about the list operations here - they're quite handy for situations like this!
Just to clarify why you get an IndexError:
When you create the new_list variable, it has a length of 0 and you try to access the the first element, which does not exists.
So in order to let the list grow as you need it you could use the append method. Then your code should look something like this:
deck = range(0,8)*2
new_list = []
for card in deck:
new_list.append(False)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With