Shape of list of lists python
Show
Creating a list of lists in python is a little tricky. In this article, we will discuss 4 different ways to create and initialize list of lists. Wrong way to create & initialize a list of lists in pythonLet’s start from basic, quickest way to create and initialize a normal list with same values in python is, All entries in the list have the same ID i.e. they point to the same list object. Why does it matter ? Let’s inserting an element in the 3rd sub list of main list i.e. Element was inserted in all the sub lists, because these are not different lists. We didn’t expect this at first place, we just wanted to insert the element in the 3rd sub-list. So, it proves that this is a wrong way to create and initialize a list of list. Let’s look at the correct way, Correct way to Create & Initialize a list of lists in pythonLet’s see 4 different but correct ways to create and initialize a list of lists Use for loop to Create & Initialize list of listsSuppose we want to create a list, which internally contains 5 different sub lists. To do that, first we will create an new empty list,then we will iterate from numbers 0 to 4 using a for loop and in each iteration, we will append an empty list to the new list i.e. All the sub lists have different IDs, which confirms that these are different objects. Let’s insert the element in the 3rd sub list, Element is added only in the 3rd sub list, all other sub lists are not affected. So, it also confirms that all the sub lists are not the references of the same list, instead they are completely different objects. Use List Comprehension & range() to create a list of listsUsing Python’s range() function, we can generate a sequence of numbers from 0 to n-1 and for each element in the sequence create & append a sub-list to the main list using List Comprehension i.e. It proves that all sub lists have different Identities. Use List Comprehension & repeat() to create a list of listsIn python itertools module provide a function repeat(), It proves that all sub lists have different Identities.Although, this is one of the least used method to create a list of lists, but still it is good to know different things because once you know the APIs and their use cases, then you can apply it to some other scenarios. Use Numpy to create a list of listsNumpy module in python provides a function empty() to create a empty Numpy array of given shape i.e. It returns a new Numpy array of given shape. So, now to create a list of lists, we will create a 2D Numpy array using empty() function and will then convert it into a list of lists using numpy.tolist() function. For example, It proves that all sub lists are different objects. The complete example is as follows, |