-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!

4
  • 1
    You just built a nested loop Commented Dec 12, 2019 at 9:40
  • print (*((f,l) for f,l in zip(first_names,last_names))) Commented Dec 12, 2019 at 9: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? Commented Dec 12, 2019 at 9:41
  • Does this answer your question? Problem in looping two for loops at the same time in python Commented Dec 12, 2019 at 9:42

2 Answers 2

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')
Sign up to request clarification or add additional context in comments.

2 Comments

Why not call str.title once?
Just slipped my mind. Edited.
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.