Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make multiple empty lists in python?

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?

like image 381
Sameer Patel Avatar asked Nov 22 '12 22:11

Sameer Patel


People also ask

How do you create an empty list in Python?

You can create an empty list using an empty pair of square brackets [] or the type constructor list() , a built-in function that creates an empty list when no arguments are passed. Square brackets [] are commonly used in Python to create empty lists because it is faster and more concise.

How do I make a list of multiple lists in Python?

You can simply use a for loop to create n lists. The variable a_i changes as i increments, so it becomes a_1, a_2, a_3 ... and so on. Show activity on this post. there is a way to do that if you want to create variables.

How do you create an n list in Python?

In Python, a list is created by placing elements inside square brackets [] , separated by commas. A list can have any number of items and they may be of different types (integer, float, string, etc.). A list can also have another list as an item.


1 Answers

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]] 
like image 129
Eric Avatar answered Sep 22 '22 03:09

Eric