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?
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.
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.
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.
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]]
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