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?
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.
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.
In Javascript, doing: var array = []; creates an empty array.
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
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) ]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With