How can I make multiple empty lists in python?

2020-02-02 11:41发布

How can I make many empty lists without manually typing

list1=[] , list2=[], list3=[]

Is there a for loop that will make me 'n' number of such empty lists?

7条回答
聊天终结者
2楼-- · 2020-02-02 12:18

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]]
查看更多
家丑人穷心不美
3楼-- · 2020-02-02 12:19

How about this.

def mklist(n):
    for _ in range(n):
        yield []

Usage:

list(mklist(10))
[[], [], [], [], [], [], [], [], [], []]

a, b, c = mklist(3) # a=[]; b=[]; c=[]
查看更多
混吃等死
4楼-- · 2020-02-02 12:32

You can also add a list of list of list of list... like this too. It won't return any error. But i got no idea what it's use for.

n = 5 
>>> lists = [[[]]] for _ in range(n)]
>>> lists
   [[[[]]], [[[]]], [[[]]], [[[]]], [[[]]]]
查看更多
甜甜的少女心
5楼-- · 2020-02-02 12:32

I see that many answers here get you many lists with no names assigned (as elements of a larger list). This may be not always what's needed. It is possible to create multiple empty lists, each with a different name/value, using a tuple:

a,b,c = ([],[],[])

changing this structure should get you what you want.

查看更多
成全新的幸福
6楼-- · 2020-02-02 12:35

Lookup list comprehensions

listOfLists = [[] for i in range(N)]

Now, listOfLists has N empty lists in it

More links on list comprehensions:

1 2 3

Hope this helps

查看更多
三岁会撩人
7楼-- · 2020-02-02 12:39

If you want to create different lists without a "list of lists", try this:

list1, list2, list3, list4 = ([] for i in range(4))
查看更多
登录 后发表回答