Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list.
Code : Initializing 1D-list list in Python
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
list1 : [0, 0, 0, 0, 0] list2 : [0, 0, 0, 0, 0]
Here, Only difference is star operator is used outside of the list. And range() is used inside. These two can also be used with a list within the list or Multidimensional list.
Code : list within list using * operation and range()
list1 : [, , , , ] list2 : [, , , , ]
The real glitch is with the multidimensional list. While dealing with a multidimensional list, initialization method matters a lot. Both methods * operator and list comprehension behaves differently.
Code : Multi-dimensional List
Star list : [8, [0, 8], [0, 8], [0, 8], [0, 8]] Range list : [8, , [0, 8], , ]
If someone wants to deal with 1D-array, one can use anything. But with the multidimensional array, one should use list comprehension.