0

So I'm starting to learn python as it's an awesome language from what I've already done in it.
I came across an exercise to learn lists and it was basically as follows

Create a list of first names and a list of second names and use a for loop to print out all the full names.

So heres my lists

names = ["Jake", "Ben", "Rob"]
surnames = ["Cowton", "Fielding", "Spenceley Jones"]

and heres what I tried first

for i in names:
    for j in surnames:
        print(i + " " + j)

Which obviously is wrong.
I then worked out I should do this

for i in range(0, len(names)):
    print(names[i] + " " + surnames[i])

Which gave me what I wanted.

However, I'm now thinking, is there a way of iterating through two lists in one for loop to shorted this solution. For example something like this

for x, y in names, surnames:
    print(x + " " + y)

I know this doesn't compile, but does anybody know if theres a way of doing this?

4
Contributors
3
Replies
44
Views
4 Years
Discussion Span
Last Post by Lardmeister
4

Hello, RockJake. Is something like this what you're looking for?

from itertools import *

for x in izip(names,surnames):
    print "%s %s" % x

I tested it on Python 2.7. Which version are you using?

PS: Forgot to mention that izip is a function from the itertools module found in the standard library (http://docs.python.org/2/library/itertools.html). Sorry about that.

Edited by Crimson King

2

As posted over itertools izip is ok to use and fast.
Python has also build in zip

>>> zip(names,surnames)
[('Jake', 'Cowton'), ('Ben', 'Fielding'), ('Rob', 'Spenceley Jones')]

---

for first,last in zip(names,surnames):
    print first,last

    Jake Cowton
    Ben Fielding
    Rob Spenceley Jones        
0

Another option, using Python27 or higher:

names = ["Jake", "Ben", "Rob"]
surnames = ["Cowton", "Fielding", "Spenceley Jones"]

for ix, first in enumerate(names):
    print("{} {}".format(first, surnames[ix]))

''' output >>>
Jake Cowton
Ben Fielding
Rob Spenceley Jones
'''

Using zip() is more elegant and takes care of lists with different length.

Edited by Lardmeister

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.