snk
snk

Reputation:

In Python, can I print 3 lists in order by index number?

So I have three lists:

['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]

Is there a way that would allow me to print the values in these lists in order by index?

e.g.

this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all items at list[1])
the, 3, 0.3 (all items at list[2])
first, 4, 0.04 (all items at list[3])
list, 5, 0.05 (all items at list[4])

The number of items in each list varies each time the script is run, but they always end up with the same number of values in the end. So, one time, the script could create three arrays with 30 items, another time, it could create only 15 values in each, etc.

Upvotes: 7

Views: 8697

Answers (4)

cwallenpoole
cwallenpoole

Reputation: 82058

This is the most immediately obvious way (to a python newb), and there is likely a better way, but here goes:

#Your list of lists.
uberlist = ( list1, list2, list3 )

#No sense in duplicating this definition multiple times.
#Define it up front.
uberRange = range( len( uberList ) );

#Since each will be the same length, you can use one range.
for i in range( len( list1 ) ):
    # Iterate through the sub lists.
    for j in uberRange:
        #Output
        print uberlist[ j ][ i ];

Upvotes: 0

Jochen Ritzel
Jochen Ritzel

Reputation: 107666

lists = ( ['this', 'is', 'the', 'first', 'list'], 
          [1, 2, 3, 4, 5], 
          [0.01, 0.2, 0.3, 0.04, 0.05])
print zip(*lists)

zips the lists together and stops when the shortest list runs out of items.

Upvotes: 1

Jack Lloyd
Jack Lloyd

Reputation: 8405

What you are probably looking for is called zip:

>>> x = ['this', 'is', 'the', 'first', 'list']
>>> y = [1, 2, 3, 4, 5]
>>> z = [0.01, 0.2, 0.3, 0.04, 0.05]
>>> zip(x,y,z)
[('this', 1, 0.01), ('is', 2, 0.20000000000000001), ('the', 3, 0.29999999999999999), ('first', 4, 0.040000000000000001), ('list', 5, 0.050000000000000003)]
>>> for (a,b,c) in zip(x,y,z):
...     print a, b, c
... 
this 1 0.01
is 2 0.2
the 3 0.3
first 4 0.04
list 5 0.05

Upvotes: 9

mthurlin
mthurlin

Reputation: 27295

Use zip

for items in zip(L1, L2, L3):
    print items

items will be a tuple with a value from each list, in order.

Upvotes: 3

Related Questions