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’
['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.
Frequently Asked:
- Convert a List of floats to List of integers in Python
- Check if all values in List are False in Python
- Python : Check if a list contains all the elements of another list
- Get unique values from a List in Python
['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']
This is an absolutely brilliant website!
I have been away from IT for over 8 years, and I am making a return to this industry due to the large shortage of IT professionals. I have therefore been learning new skills and relearning old skills.
I have been covering both Python and C++ in detail, along with MySQL, PHP, SQL, PL/SQL and testing, the last 3 I am very familiar with.
This site gives me all sorts of very useful information that I need and how to solve problems the best way possible.