* 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
list1 = [ 0 ] * 5
list2 = [ 0 for i in range ( 5 )]
print ( "list1 : " , list1)
print ( "list2 : " , list2)
|
Output:
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 = [[ 0 ]] * 5
list2 = [[ 0 ] for i in range ( 5 )]
print ( "list1 : " , list1)
print ( "list2 : " , list2)
|
Output:
list1 : [[0], [0], [0], [0], [0]]
list2 : [[0], [0], [0], [0], [0]]
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 = [[ 0 ]] * 5
range_list = [[ 0 ] for i in range ( 5 )]
star_list[ 0 ] = 8
range_list[ 0 ] = 8
star_list[ 2 ].append( 8 )
range_list[ 2 ].append( 8 )
print ( "Star list : " , star_list)
print ( "Range list : " , range_list)
|
Output:
Star list : [8, [0, 8], [0, 8], [0, 8], [0, 8]]
Range list : [8, [0], [0, 8], [0], [0]]
If someone wants to deal with 1D-array, one can use anything. But with the multidimensional array, one should use list comprehension.