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
Associating a single value with all list items in Python
We may have a need to associate a given value with each and every element of a list. For example ? there are the names of the days and we want to attach the word "day" as a suffix to them. Such scenarios can be handled in the following ways.
Using itertools.repeat
We can use the repeat method from the itertools module so that the same value is used again and again when paired with the values from the given list using the zip function ?
from itertools import repeat
days = ['Sun', 'Mon', 'Tues']
val = 'day'
print("The Given list:", days)
print("Value to be attached:", val)
# With zip() and itertools.repeat()
res = list(zip(days, repeat(val)))
print("List with associated values:\n", res)
The Given list: ['Sun', 'Mon', 'Tues']
Value to be attached: day
List with associated values:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]
Using lambda and map
The lambda function creates a tuple for each list element, pairing it with the given value. The map function ensures all elements from the list are covered in this pairing process ?
days = ['Sun', 'Mon', 'Tues']
val = 'day'
print("The Given list:", days)
print("Value to be attached:", val)
# With map and lambda
res = list(map(lambda i: (i, val), days))
print("List with associated values:\n", res)
The Given list: ['Sun', 'Mon', 'Tues']
Value to be attached: day
List with associated values:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]
Using List Comprehension
A more Pythonic approach uses list comprehension to create tuples directly ?
days = ['Sun', 'Mon', 'Tues']
val = 'day'
print("The Given list:", days)
print("Value to be attached:", val)
# With list comprehension
res = [(item, val) for item in days]
print("List with associated values:\n", res)
The Given list: ['Sun', 'Mon', 'Tues']
Value to be attached: day
List with associated values:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
itertools.repeat |
Good | Fast | Large lists |
map + lambda |
Moderate | Good | Functional programming style |
| List comprehension | Excellent | Fast | Most Python scenarios |
Conclusion
All three methods effectively associate a single value with every list item. List comprehension is the most Pythonic and readable approach for most use cases, while itertools.repeat offers excellent performance for large datasets.
