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?

Recommended Answers

All 3 Replies

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.

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        

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.