Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the first word and second word using list comprehensions

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')]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading