Connecting Tech Pros Worldwide Help | Site Map

Generating a list of tuples

Member
 
Join Date: Jun 2007
Posts: 89
#1: Apr 15 '09
Looking for the classiest way to do this, just for fun. Say you have a list of names

Expand|Select|Wrap|Line Numbers
  1. names=['george', 'paul', 'john', 'ringo']
and a location string:

Expand|Select|Wrap|Line Numbers
  1. location='liverpool'
Now you want to combine these into a list of tuples based on location:

[('george','liverpool'), ('paul','liverpool'), ('john','liverpool'), ('ringo','liverpool')]

Kind of like a zip function but with all values from names present and kind of like a map function but with the location used not None. So a little twist on some common functions. Thoughts?
bvdet's Avatar
Moderator
 
Join Date: Oct 2006
Location: Nashville, TN
Posts: 1,563
#2: Apr 15 '09

re: Generating a list of tuples


Following are two ways. You can decide how classy they are.
Expand|Select|Wrap|Line Numbers
  1. def zip_location(seq, location):
  2.     return [(item,location) for item in seq]
  3.  
  4. def zip_location(seq, location):
  5.     return zip(seq, [location for i in range(len(seq))])
Reply


Similar Python bytes