![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 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
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
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')]
Advertisements