
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Similar Value Multiple Times in a Python List
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
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
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
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! ']