1

I'm trying to figure out how to add a sub-list to a list in Python. For example, the code I was using before was just:

pop = [[],[],[],[],[],[],[],[],[],[]]

But I want to add user input to the length of the pop array, ie. how many arrays are added. I've looked at some other stackoverflow questions, and some of them suggested something like:

popLen = 5
pop = [None]*popLen

But when I try that it creates a list with 5 None elements instead of an empty array. I've tried:

pop = [[]]*popLen

What's the proper way to sub-lists?

Student Loans
  • 303
  • 1
  • 4
  • 10

2 Answers2

4

pop = [[]]*popLen should work, but it is likely not what you want since it creates a list filled with the same nested list popLen times, meaning that a change to one of the list elements would appear in the others:

>>> a = [[]] * 3
>>> a[0].append(42)
>>> a
[[42], [42], [42]]

A better alternative would be

pop = [[] for _ in range(popLen)]  # use xrange() in Python 2.x

which eliminates this issue:

>>> a = [[] for _ in range(3)]
>>> a[0].append(42)
>>> a
[[42], [], []]
arshajii
  • 127,459
  • 24
  • 238
  • 287
3

You can do:

pop = [[] for x in range(popLen)]

Don't try to multiply [[]] - that will actually work, but will do something different than you expect (it will give you copies of the same list, so you cannot change them independently).

viraptor
  • 33,322
  • 10
  • 107
  • 191