I’m not sure how to get the first word from the list ‘meeps’ and the second word from the list ‘peeps’. This is the code I have so far through list comprehensions.
meeps = ["Foghorn Leghorn", "Elmer Fudd", "Road Runner", "Bugs Bunny", "Daffy Duck", "Tasmanian Devil"]
peeps = ["John Cleese", "Michael Palin", "Terry Gilliam", "Terry Jones", "Graham Chapman","Eric Idle"]
mashemup1 = [(x.split()[0], y.split()[1]) for x in meeps for y in peeps]
print(mashemup1)
It prints the list like this:
[('Foghorn', 'Cleese'), ('Foghorn', 'Palin'), ('Foghorn', 'Gilliam'), ('Foghorn', 'Jones'), ('Foghorn', 'Chapman'), ('Foghorn', 'Idle'), ('Elmer', 'Cleese'), ('Elmer', 'Palin'), ('Elmer', 'Gilliam'), ('Elmer', 'Jones'), ('Elmer', 'Chapman'), ('Elmer', 'Idle'), ('Road', 'Cleese'), ('Road', 'Palin'), ('Road', 'Gilliam'), ('Road', 'Jones'), ('Road', 'Chapman'), ('Road', 'Idle'), ('Bugs', 'Cleese'), ('Bugs', 'Palin'), ('Bugs', 'Gilliam'), ('Bugs', 'Jones'), ('Bugs', 'Chapman'), ('Bugs', 'Idle'), ('Daffy', 'Cleese'), ('Daffy', 'Palin'), ('Daffy', 'Gilliam'), ('Daffy', 'Jones'), ('Daffy', 'Chapman'), ('Daffy', 'Idle'), ('Tasmanian', 'Cleese'), ('Tasmanian', 'Palin'), ('Tasmanian', 'Gilliam'), ('Tasmanian', 'Jones'), ('Tasmanian', 'Chapman'), ('Tasmanian', 'Idle')]
>Solution :
You can use zip to process two lists in parallel. Zip will stop iteration at the shorter of the two lists.
mashemup = [x.split()[0] + ' ' + y.split()[1] for x, y in zip(meeps, peeps)]
print(mashempup)
['Foghorn Cleese', 'Elmer Palin', 'Road Gilliam', 'Bugs Jones', 'Daffy Chapman', 'Tasmanian Idle']
Or if you need a list of tuples:
mashemup = [(x.split()[0], y.split()[1]) for x, y in zip(meeps, peeps)]
print(mashempup)
[('Foghorn', 'Cleese'), ('Elmer', 'Palin'), ('Road', 'Gilliam'), ('Bugs', 'Jones'), ('Daffy', 'Chapman'), ('Tasmanian', 'Idle')]