How to Make Multiple Empty Lists in Python

How can I make multiple empty lists in Python?

A list comprehension is easiest here:

>>> n = 5
>>> lists = [[] for _ in range(n)]
>>> lists
[[], [], [], [], []]

Be wary not to fall into the trap that is:

>>> lists = [[]] * 5
>>> lists
[[], [], [], [], []]
>>> lists[0].append(1)
>>> lists
[[1], [1], [1], [1], [1]]

How to make a loop in Python which creates multiple empty lists?

Highly advise against this but this achieves what you want depending on your use case:

globals()['list_' + str(i)] = []

for i in range(5):
globals()['list_' + str(i)] = []

list_1
[]

list_2
[]

etc...

Depending on your use case switch globals for locals and vice-versa.

A better idea would be defaultdict

from collections import defaultdict

my_lists = defaultdict(list)

Now you don't have to initialize any list until you use it and every key comes with it's value being a list already. For example:

for i in range(5):
my_lists['list_' + str(i)].append('foo')

my_lists

defaultdict(list,
{'list_0': ['foo'],
'list_1': ['foo'],
'list_2': ['foo'],
'list_3': ['foo'],
'list_4': ['foo']})

How do i create declare with multiple empty lists in python

Values (such as 3, "hello", True, [], etc) are referenced by variables, which have a name. For example:

a = 4

a is a variable (whose name is "a"), and it references the 4 value.

Not all names are valid though. For example, "1" is not a valid name for a variable. How could the interpreter know that 1 is a variable and not a value?

Moreover, you can't assign a value to another value. I.e., you can't do something like this:

4 = True

It simply doesn't make any sense.

In your specific case, str(y) is an expression that returns a value. For example, if y=3 then str(y) would return "3". Being a value, you can't assign to it another value! I.e., you can't do

str(y) = []

Instead, you might want to create a variable (with a proper name) and assign a value to it.

If you really want to create a variable with a name generated at runtime, you might want to look at this question. It is not recommended though. Instead, you might want to create an array of values:

arr = []
for i in range(100):
arr.append([])
# arr[i] is your i-th variable

How to create multiple (but individual) empty lists in Python?

You are overcomplicating things. Just use a list or dictionary:

fields = {key: [] for key in 'ABCD'}

then refer to fields['A'], etc. as needed, or loop over the structure to process each in turn.

Initialization of multiple empty lists in Python

Why the first attempt does not allocate a, b independently in memory? because they refer to same address in memory.

(a, b) = ([],)*2
print(id(a))
print(id(b))
# 4346159296
# 4346159296
(a, b) = ([]  for _ in range(2))
print(id(a))
print(id(b))
# 4341571776
# 4341914304

Creating multiple lists in python or empty arrays

Here are a couple of options:

1. A basic list comprehension:

seven_lists = [[] for i in range(7)]

Which gives a nested list of seven lists:

[[], [], [], [], [], [], []]

2. A list of (day, []) tuples:

days = [("day " + str(i+1), []) for i in range(7)]

Which gives:

[('day 1', []), ('day 2', []), ('day 3', []), ('day 4', []), ('day 5', []), ('day 6', []), ('day 7', [])]

3. A dictionary of days:

days = {"day " + str(i+1) : [] for i in range(7)}

Which gives:

{'day 1': [], 'day 2': [], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}

And then you can access/update each/multiple days like this:

>>> days['day 1']
[]
>>> days['day 1'].append(1)
>>> days['day 1']
[1]
>>> days
{'day 1': [1], 'day 2': [], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}
>>> days.update({'day 2': [1, 2, 3]})
>>> days
{'day 1': [1], 'day 2': [1, 2, 3], 'day 3': [], 'day 4': [], 'day 5': [], 'day 6': [], 'day 7': []}

Automatically generate empty lists in python

You could make a dictionary, where each key is the name of the list, and each value contains an empty list.

n = 3
dic = {f'list{i}': [] for i in range(1, n+1)}
print(dic)

Output:

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

Creating multiple empty list seperated by comma

With a Pandas dataframe, what you desire is not possible. The name Pandas is derived from "panel data". As such, it's built around NumPy arrays, one for each series or "column" of data. You can't have "placeholders" for series which should be skipped over when exporting to a CSV or Excel file.

You can explicitly set your index equal to your dataframe values and then use pd.DataFrame.reindex with a list of letters. If you have more than 26 columns, see Get Excel-Style Column Names from Column Number.

import pandas as pd
from string import ascii_lowercase

data = [['a'], ['b'], ['c'], ['d'], ['e'], ['o']]

df = pd.DataFrame(data)
df.index = df[0]

df = df.reindex(list(ascii_lowercase)).T.fillna('')

print(df[list('abcdefg') + list('mnopqrs')])

0 a b c d e f g m n o p q r s
0 a b c d e o

Python - Initializing Multiple Lists/Line

alist, blist, clist, dlist, elist = ([] for i in range(5))

The downside of above approach is, you need to count the number of names on the left of = and have exactly the same number of empty lists (e.g. via the range call, or more explicitly) on the right hand
side.

The main thing is, don't use something like

alist, blist, clist, dlist, elist = [[]] * 5

nor

alist = blist = clist = dlist = elist = []

which would make all names refer to the same empty list!



Related Topics



Leave a reply



Submit