4

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

Ekaterina1234
  • 400
  • 1
  • 7
  • 20

2 Answers2

6

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!

Aurora0001
  • 13,139
  • 5
  • 50
  • 53
  • This is a neat solution, but beware that for "complex" types, the resulting list will have `n` copies of the *same* object, rather than `n-1` copies added to the list. – schlimmchen Aug 24 '17 at 15:23
2

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)
wastl
  • 2,643
  • 14
  • 27