Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of empty lists

Tags:

python

list

Apologies if this has been answered before, but I couldn't find a similar question on here.

I am pretty new to Python and what I am trying to create is as follows:

list1 = [] list2 = [] results = [list1, list2] 

This code works absolutely fine, but I was wondering if there was a quicker way to do this in one line.

I tried the following, which didn't work, but I hope it demonstrates the sort of thing that I'm after:

result = [list1[], list2[]] 

Also, in terms of complexity, would having it on one line really make any difference? Or would it be three assignments in either case?

like image 392
daemon_headmaster Avatar asked Nov 30 '15 02:11

daemon_headmaster


People also ask

How do you create an empty list in a list?

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.

Can you make a list of lists in Python?

In Python, we can create a list by surrounding all the elements with square brackets [] and each element separated by commas. It can be used to store integer, float, string and more. Python provides an option of creating a list within a list.

How do you create an empty list in HTML?

In Javascript, doing: var array = []; creates an empty array.


2 Answers

For arbitrary length lists, you can use [ [] for _ in range(N) ]

Do not use [ [] ] * N, as that will result in the list containing the same list object N times

like image 92
roeland Avatar answered Oct 04 '22 16:10

roeland


For manually creating a specified number of lists, this would be good:

empty_list = [ [], [], ..... ] 

In case, you want to generate a bigger number of lists, then putting it inside a for loop would be good:

empty_lists = [ [] for _ in range(n) ] 
like image 31
Dawny33 Avatar answered Oct 04 '22 18:10

Dawny33