Associating a single value with all list items in Python

PythonServer Side ProgrammingProgramming

We may have a need to associate a given value with each and every element of a list. For example − there are the name of the days and we want to attach the word day as a suffix in them. Such scenarios can be handled in the following ways.

With itertools.repeat

We can use the repeat method from 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.

Example

 Live Demo

from itertools import repeat

listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With zip() and itertools.repeat()
res = list(zip(listA, repeat(val)))
print ("List with associated vlaues:\n" ,res)

Output

Running the above code gives us the following result −

The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]

With lambda and map

The lambda method makes and iteration over the list elements and starts pairing them. The map function ensures all elements form the list are covered in pairing the list elements with the given value.

Example

 Live Demo

listA = ['Sun','Mon','Tues']
val = 'day'
print ("The Given list : ",listA)
print ("Value to be attached : ",val)
# With map and lambda
res = list(map(lambda i: (i, val), listA))
print ("List with associated vlaues:\n" ,res)

Output

Running the above code gives us the following result −

The Given list : ['Sun', 'Mon', 'Tues']
Value to be attached : day
List with associated vlaues:
[('Sun', 'day'), ('Mon', 'day'), ('Tues', 'day')]
raja
Published on 10-Jul-2020 09:43:17
Advertisements