Hello All

This is my first post in this forum, despite my long visiting hours as a guest:D
I don't have any background in programming and I'm a newbie in python too. But Learning python for S60(Python distro for Symbian Phones.

anyway, I have a problem with printing from two lists.
what I'm trying to do is printing something like "Item1(from list1):::Item1(from list2)" for each item in both lists:

list1 = [Item1, Item2, Item3,... ItemN]
list2=[Item1, Item2, Item3,... ItemN]
for i in list1:
    for j in list2:
        print '%s:::%s'%(i,j)

this code doesn't give the result I want.
Python Experts please give me a hint how to do this.
any help or suggestion will be more than appreciated.
thanks in Advance

PS: sorry my bad English

Recommended Answers

All 4 Replies

Hint

>>> list1 = range(10)
>>> list2 = range(100, 110)
>>> list1
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list2
[100, 101, 102, 103, 104, 105, 106, 107, 108, 109]
>>> list3 = zip(list1, list2)
>>> list3
[(0, 100), (1, 101), (2, 102), (3, 103), (4, 104), (5, 105), (6, 106), (7, 107), (8, 108), (9, 109)]

Edit: in python 3, use list(zip(list1, list2))

Really Thank you Gribouillis for your fast reply.

Yes! zip is what I was in need of Exactly.

I came up with this:

list1=['Item1', 'Item2', 'Item3', 'Item4']
list2=['1','2','3','4']

for i,j in zip(list1, list2):
    print '%s______%s'%(j, i)

and the Result:

1______Item1
2______Item2
3______Item3
4______Item4

Just Curious, Can it be done in another way?

Really Thank you Gribouillis for your fast reply.

Yes! zip is what I was in need of Exactly.

I came up with this:

list1=['Item1', 'Item2', 'Item3', 'Item4']
list2=['1','2','3','4']

for i,j in zip(list1, list2):
    print '%s______%s'%(j, i)

and the Result:

1______Item1
2______Item2
3______Item3
4______Item4

Just Curious, Can it be done in another way?

It can always be done in different ways, but zip is the correct tool. You could loop on indexes

for i, item1 in enumerate(list1):
    item2 = list2[i]
    # do something with item1 and item2

You could also use a generator

def my_strings(list1, list2):
    it1, it2 = iter(list1), iter(list2)
    while True:
        yield "%s____%s" % (next(it1), next(it2))

for s in my_strings(list1, list2):
    print s

Thanks a lot again Gribouillis for additional info.

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.