2

I am trying to print things from 2 lists one after another.

ls1 = ['Apple', 'Orange', 'Banana', 'Morty']
ls2 = ['Pineapple', 'Carrot', 'Rick', 'Tangelo']

I would usually do:

for fruit in ls1:
    print(fruit)
for fruit in ls2
    print(fruit)

but that will cycle though one list then the other. I want the output to alternate between the lists in order:

Apple
Pineapple
Orange
...etc...

or

ls1[0]
ls2[0]
ls1[1]
ls2[1]
...etc...
Rahul
  • 10,830
  • 4
  • 53
  • 88
Mark
  • 425
  • 1
  • 4
  • 19
  • If list are of different size take a look into: https://stackoverflow.com/a/19686624/5916727 – niraj Jul 18 '17 at 04:44

4 Answers4

5

IMHO a more pythonic way would be:

ls_1 = ["Apple", "Orange", "Banana", "Morty"]
ls_2 = ["Pineapple", "Carrot", "Rick", "Tangelo"]

for i, j in zip(ls_1, ls_2):
    print(i, j)
RinkyPinku
  • 410
  • 3
  • 20
igortg
  • 150
  • 9
3
for i in range(len(ls1)):
    print(ls1[i])
    print(ls2[i])

given if length of ls1 is equal to length of ls2

Nimish Bansal
  • 1,719
  • 4
  • 20
  • 37
3

Zip is more reliable here

for i, j in zip(ls1, ls2):
    print(i)
    print(j)

zip takes care if your list are not of same length.

it stops at the length of a shorter list.

Rahul
  • 10,830
  • 4
  • 53
  • 88
2

I would take care of different sizes of both the list scenario too.

ls1 = ['Apple', 'Orange', 'Banana', 'Morty', 'Cherries', 'Avacado']
ls2 = ['Pineapple', 'Carrot', 'Rick', 'Tangelo']

for i in range(max(len(ls1), len(ls2))):
    if (i < len(ls1)):
        print(ls1[i])
    if (i < len(ls2)):
        print(ls2[i])
JRG
  • 4,037
  • 3
  • 23
  • 34