Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add similar value multiple times in a Python list
There are occasions when we need to add the same value multiple times to a Python list. This is useful for initializing lists, creating test data, or padding sequences. Python provides several built-in methods to achieve this efficiently.
Using the * Operator
This is the most straightforward method. The * operator creates a new list by repeating elements a specified number of times.
Example
Creating a list with repeated strings ?
given_value = 'Hello! ' repeated_list = [given_value] * 5 print(repeated_list)
The output of the above code is ?
['Hello! ', 'Hello! ', 'Hello! ', 'Hello! ', 'Hello! ']
You can also repeat numbers or other data types ?
numbers = [0] * 5
print("Numbers:", numbers)
mixed = [42, 'test'] * 3
print("Mixed:", mixed)
Numbers: [0, 0, 0, 0, 0] Mixed: [42, 'test', 42, 'test', 42, 'test']
Using itertools.repeat()
The itertools.repeat() function creates an iterator that returns the same value repeatedly. Use list() to convert it to a list.
Example
from itertools import repeat given_value = 'Hello! ' repeated_list = list(repeat(given_value, 5)) print(repeated_list)
['Hello! ', 'Hello! ', 'Hello! ', 'Hello! ', 'Hello! ']
Using List Comprehension
List comprehension provides a readable way to create repeated values, especially when you need more complex logic.
Example
given_value = 'Hello! '
repeated_list = [given_value for i in range(5)]
print(repeated_list)
# With enumeration
indexed_list = [f"{given_value}{i}" for i in range(3)]
print("Indexed:", indexed_list)
['Hello! ', 'Hello! ', 'Hello! ', 'Hello! ', 'Hello! '] Indexed: ['Hello! 0', 'Hello! 1', 'Hello! 2']
Comparison
| Method | Syntax | Best For |
|---|---|---|
* operator |
[value] * n |
Simple repetition |
itertools.repeat() |
list(repeat(value, n)) |
Memory-efficient for large lists |
List comprehension |
[value for i in range(n)] |
Complex logic or modifications |
Conclusion
Use the * operator for simple repetition, itertools.repeat() for memory efficiency, and list comprehension when you need to modify values during repetition. Each method creates a new list with the specified number of repeated elements.
