We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Python : How to create a list and initialize with same values

In this article we will discuss how to create a list and initialise with same values.

Creating a list of same values by [] and multiply

Suppose we want to create a list of strings, which contains 20 same strings i.e. ‘Hi’

Advertisements

['Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi']

Let’s see how to do that i.e.

''' create a list by [] and multiply by repeat count '''
listOfStrings1 = ['Hi'] * 20

[‘Hi’] will create a list with single value, then we can multiply this list by 20. It will repeat the contents of list 20 times.
So, lists content will be now i.e.

['Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi']

Creating a list of same values by List Comprehension with range()

This is an another way to create a list of same value using range() i.e.

''' 
    Use List Comprehension with range() to initialize a list by 20 elements 0
    It will iterate over the tange from 0 to 20 and for
    each entry, it will add 'Hi' to the list and in the end 
    returns the list to listOfNums
'''
listOfStrings2 = ['Hi' for i in range(20)]

In this list comprehension, for loop will iterate over the range object 20 times and in each iteration it will add ‘Hi’ in the list.
So, list will coatain 20 ‘Hi’ elements i.e.

['Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi']

Complete example is as follows,

def main():
    
    ''' create a list by [] and multiply by repeat count '''
    listOfStrings1 = ['Hi'] * 20

    print(listOfStrings1)
    

    ''' 
    Use List Comprehension with range() to initialize a list by 20 elements 0
    It will iterate over the tange from 0 to 20 and for
    each entry, it will add 'Hi' to the list and in the end 
    returns the list to listOfNums
    '''
    listOfStrings2 = ['Hi' for i in range(20)]
    
    print(listOfStrings2)
    
    
if __name__ == '__main__':
    main()

Output:

['Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi']
['Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi', 'Hi']

 

Cart

Your Cart is Empty

Back To Shop