-1

I have two lists -

lst1 = ["apple", "orange", "banana"]
lst2 = ["cherry", "grape", "pear"]

I want to print in this sequence-

apple
orange
banana
cherry
grape
pear

How do I do this in 1 for loop?

EDIT: to clarify my question - I don't want to add the two lists into a 3rd list and then print. Can I do it directly in a single for loop?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
access_nash
  • 35
  • 1
  • 5
  • 1
    concatenate 2 lists, and print out the elements – ZdaR Jun 01 '15 at 12:35
  • http://stackoverflow.com/questions/1720421/merge-two-lists-in-python – vaultah Jun 01 '15 at 12:39
  • to clarify my question - I don't want to add the two lists into a 3rd list and then print. Can I do it directly in a single for loop? – access_nash Jun 01 '15 at 12:40
  • 2
    2 loops: `for x in lst1: print(x)` and then `for x in lst2: print(x)` Otherwise use `itertools.chain`. – vaultah Jun 01 '15 at 12:41
  • had mentioned "single for loop". anyway, it's working fine now. thanks – access_nash Jun 01 '15 at 12:50
  • @access_nash could you elaborate on the solution you found acceptable? – Paul Rooney Jun 01 '15 at 20:57
  • the solution mentioned by alec_djinn works fine. Initially I had done that, but for some reason got an error - "too many items to unpack". Which is why I thought I might be doing something wrong while adding lists of different sizes (Btw, I wasn't working on the exact lists as mentioned above. I wanted something similar, so gave a simple example). – access_nash Jun 02 '15 at 12:48

3 Answers3

5

You want to chain the lists together (not the same as creating a third list):

from itertools import chain

# ...
for item in chain(lst1, lst2):
    # ...

If you have more than 2 lists:

for item in chain(lst1, lst2, lst3, lst4):

chain is very efficient: it does not create a new list.

Hai Vu
  • 37,849
  • 11
  • 66
  • 93
1

If you have a list of lists you should use the unpacking operator * and itertools.chain:

lsts = [["apple", "orange", "banana"],["cherry", "grape", "pear"]]
for item in chain(*lsts):
    print item

This will work if you don't know how many lists there are.

Sebastian Wozny
  • 16,943
  • 7
  • 52
  • 69
0

This is a rather easy question that you may solve just reading up the very beginning of the python documentation... However... this is the answer.

for item in (lst1+lst2):
    print item
alec_djinn
  • 10,104
  • 8
  • 46
  • 71