Add similar value multiple times in a Python list

PythonServer Side ProgrammingProgramming

There are occasions when we need to show the same number or string multiple times in a list. We may also generate these numbers or strings for the purpose of some calculations. Python provides some inbuilt functions which can help us achieve this.

Using *

This is the most used method. Here we use the * operator which will create a repetition of the characters which are mentioned before the operator.

Example

 Live Demo

given_value ='Hello! '
repeated_value = 5*given_value
print(repeated_value)

Running the above code gives us the following result:

Hello! Hello! Hello! Hello! Hello!

Using repeat

The itertools module provides repeat function. This function takes the repeatable string as parameter along with number of times the string has to be repeated. The extend function is also used to create the next item for the list which holds the result.

Example

 Live Demo

from itertools import repeat
given_value ='Hello! '
new_list=[]
new_list.extend(repeat(given_value,5))
print(new_list)

Running the above code gives us the following result:

['Hello! ', 'Hello! ', 'Hello! ', 'Hello! ', 'Hello! ']

Using extend and for loop

We can also use the extend() to create a list of the string to be repeated by using range and for loop. First we declare an empty list then keep extending it by adding elements created by the for loop. The range() decided how many times the for loop gets executed.

Example

 Live Demo

given_value ='Hello! '
new_list=[]
new_list.extend([given_value for i in range(5)])
print(new_list)

Running the above code gives us the following result:

['Hello! ', 'Hello! ', 'Hello! ', 'Hello! ', 'Hello! ']
raja
Published on 02-Jan-2020 09:27:21
Advertisements