* 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
# Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [ 0 ] * 5 # Initialize using list comprehension # list of size 5 will be initialized. # range() is used inside list. list2 = [ 0 for i in range ( 5 )]
print ( "list1 : " , list1)
print ( "list2 : " , list2)
|
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()
# Python code to # initialize list within the list # Initialize using star operator list1 = [[ 0 ]] * 5 # Initialize using range() list2 = [[ 0 ] for i in range ( 5 )] # list of 5 "[0] list" is initialized.
# Both list are same so far print ( "list1 : " , list1)
print ( "list2 : " , list2)
|
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
# Consider same previous example. # Initialize using star operator. star_list = [[ 0 ]] * 5
# Initialize using list Comprehension. range_list = [[ 0 ] for i in range ( 5 )]
star_list[ 0 ] = 8 # Expected output will come.
range_list[ 0 ] = 8 # Expected output.
''' Output: star_list = [8, [0], [0], [0], [0]]
range_list = [8, [0], [0], [0], [0]]
''' # Unexpected output will come. star_list[ 2 ].append( 8 )
''' Since star_list[2] = [0]. so it will find for all
[0] in list and append '8' to each occurrence of
[0]. And will not affect "non [0]" items is list.'''
range_list[ 2 ].append( 8 ) # expected output.
print ( "Star list : " , star_list)
print ( "Range list : " , range_list)
|
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.