Reputation: 165
I'm trying to combine a list of first- and surnames with no luck. My code is like this at the moment:
firstname=['Tom','Dick','Steve']
surname=['Johnson','Smith','Doe']
for f in (firstname):
for s in (surname):
print(f,s)
Which gives me something like this:
Tom Johnson
Tom Smith
Tom Doe
Dick Johnson
And so on, when I really want:
Tom Johnson
Dick Smith
Steve Doe
Help much appreciated for a beginner like me.
Upvotes: 3
Views: 3639
Reputation:
firstname=['Tom','Dick','Steve']
surname=['Johnson','Smith','Doe']
i = 0
while i<min(len(firstname), len(surname)):
print (firstname[i], surname[j])
i += 1
Upvotes: 0
Reputation: 4568
Zip is the way to combine two lists together in python. So, as a function,
def combine_names(first, last):
comb = zip(first, last)
for f,l in comb:
print f,l
Upvotes: 1
Reputation: 311188
Assuming both lists have the same length, you could iterate over it and use the corresponding index on both:
for i in range(len(firstname)):
print (firstname[i], surname[i])
Upvotes: 0
Reputation: 110271
for name, surname in zip(firstname, surname):
print(name, surname)
Upvotes: 6