-2

I built this Python code with the intent to match each first name with the last name:

first_names = ['Jane','Sam','Deborah']
last_names = ['Simmons','Kaybone','Stone']

for f_name in first_names:
    for l_name in last_names:
        print(f_name.title() + " " + l_name.title())

But apparently my code prints out all first names with all last_names instead of just (1,1), (2,2), (3,3). How do I tweak this code? Thanks!

user71812
  • 457
  • 2
  • 4
  • 19
  • 1
    You just built a nested loop – Chris_Rands Dec 12 '19 at 09:40
  • `print (*((f,l) for f,l in zip(first_names,last_names)))` – Fourier Dec 12 '19 at 09:41
  • If you wanted to print out `(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3), (3, 1), (3, 2), (3, 3)` how would you expect to do it? – Peter Wood Dec 12 '19 at 09:41
  • Does this answer your question? [Problem in looping two for loops at the same time in python](https://stackoverflow.com/questions/55558467/problem-in-looping-two-for-loops-at-the-same-time-in-python) – peer Dec 12 '19 at 09:42

2 Answers2

2

You are looking for zip:

first_names = ['Jane','Sam','Deborah']
last_names = ['Simmons','Kaybone','Stone']
for f, l in zip(first_names, last_names):
    print(f.title(),l.title())

Output:

Jane Simmons
Sam Kaybone
Deborah Stone

One-liner:

print(*(f'{f.title()} {l.title()}' for f, l in zip(first_names, last_names)),sep='\n')

EDIT: As pointed correctly by Peter Wood:

print(*(f'{f} {l}'.title() for f, l in zip(first_names, last_names)),sep='\n')
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
2

What you want is zip():

first_names = ['Jane','Sam','Deborah']
last_names = ['Simmons','Kaybone','Stone']

for f_name, l_name in zip(first_names, last_names):
  print(f_name + " " + l_name)
mrhd
  • 1,036
  • 7
  • 16