Tiger1
Tiger1

Reputation: 1377

Printing items in two separate lists in proper alignment using python

I am trying to print items in two separate lists in a way that items in list-1 will align with items in list-2.

Here is my attempt:

import numpy as np
list_1=[1,2,3,4]
list_2=np.arange(0.1,0.4,0.1)

for x in list_1:
    j=x/2.0
    for y in list_2:
        print j,',', y

My Output:

0.5 , 0.1
0.5 , 0.2
0.5 , 0.3
0.5 , 0.4
1.0 , 0.1
1.0 , 0.2
1.0 , 0.3
1.0 , 0.4
1.5 , 0.1
1.5 , 0.2
1.5 , 0.3
1.5 , 0.4
2.0 , 0.1
2.0 , 0.2
2.0 , 0.3
2.0 , 0.4

Desired Output:

0.5 , 0.1
1.0 , 0.2
1.5 , 0.3
2.0 , 0.4

Upvotes: 0

Views: 81

Answers (1)

Inbar Rose
Inbar Rose

Reputation: 43497

What you want is zip().

Example:

>>> l1 = range(10)
>>> l2 = range(20,30)
>>> for x,y in zip(l1, l2):
    print x, y

0 20
1 21
2 22
3 23
4 24
5 25
6 26
7 27
8 28
9 29

Explanation:

zip receives iterables, and then iterates over all of them at once, starting from the 0 element of each, then going on to the 1st and then 2nd and so on, once any of the iterables reaches the end - the zip will stop, you can use izip_longest from itertools to fill empty items in iterables with None (or you can do some fancier things - but that is for a different question)

Upvotes: 3

Related Questions