2

How can I create as many empty lists as a for loop variable determines ?

As in:

for i in range(3):
    list_{i} = []  #this is just an idea

In the end of the for loop I'd have:

list_0 = [] #empty, I could add elements later.
list_1 = [] #empty
list_2 = [] #empty

I'm new to Python so please if this question is a duplicate, let me know but I haven't found any question with the same needs.

2
  • 1
    You cannot do it that way where you end up having variables named list_0, list_1 etc. Seems like a bunch of people have replied with other alternatives that you can use instead :) Commented Jan 30, 2019 at 11:40
  • 1
    It's a shame nobody's mentioned collections.defaultdict. There's a high chance this is the solution you need. Commented Jan 30, 2019 at 12:08

4 Answers 4

3
lists_= [[] for i in range(3)]
print(lists_)

OUTPUT:

[[], [], []]

and then if you want to add elements to a specific list_:

lists_[0].append(1)
lists_[0].append(2)
lists_[0].append(3)

print(lists_[0])

OUTPUT:

[1, 2, 3]

EDIT:

Since OP mentioned that range is conditional:

cond_1 = False
if cond_1:
    x = 3
else:
    x = 2
lists_= [[] for i in range(x)]
print(lists_)

OUTPUT:

[[], []]
[1, 2, 3]
Sign up to request clarification or add additional context in comments.

4 Comments

The problem is that the number of lists is unknown, so I need to create a list based on an ifcondition, so I can't tell what's the range.
@L'recherche. whats the condition, the range can be changed accordingly as well.
I have a 2d array with 100 rows and 3 columns, so I check: if array[i][0] == 1 than create list, than i is incremented, what means that iis checking all the 100 rows. In the end if I have 20 rows with the first element equal to 1 (array[i][0] == 1), I'd need 20 lists.
@L'recherche. kindly check the edit I already made.
2

Try this:

for i in range(3): 
    globals()[f'list_{i}'] = []  # Only Python3.6 or higher

for python lower than 3.6:

for i in range(3): 
    globals()['list_{}'.format(i)] = [] 

then you will have list_0, list_1 and list_2 equals to [].

Comments

1

Either via a list comprehension:

lst = [[] for i in range(3)]

Or via .append():

lst = list()
for i in range(3):
    lst.append([])

print(lst)

Comments

1

1. You can create a list of a lists the next way using for loop

>>> pool = []
>>> for i in range(3):
>>>    pool.append([])

2. You can create it dynmicly

>>> pool = [[] for i in range(3)]

3. However if you want specify names, maby it is better to store them in a dict

>>> pool = dict([(i, []) for i in range(3)])

The output will be:

>>> pool
{0: [], 1: [], 2: []}

4. The same example with the readable names

>>> pool = dict([(i, []) for i in ['list1', 'list2', 'list3']])

The output in that example will be:

>>> pool
{'list1': [], 'list3': [], 'list2': []}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.