user3136858
user3136858

Reputation: 25

How for loop works in python?

I have a lists of lists in variable lists something like this:

[7, 6, 1, 8, 3]
[1, 7, 2, 4, 2]
[5, 6, 4, 2, 3]
[0, 3, 3, 1, 6]
[3, 5, 2, 14, 3]
[3, 11, 9, 1, 1]
[1, 10, 2, 3, 1]

When I write lists[1] I get vertically:

6
7
6
3
5
11
10

but when I loop it:

for i in list:
    print(i)

I get this horizontally.

7
6
1
8
3
etc...

So, how it works? How can I modify loop to go and give me all vertically?

Upvotes: 0

Views: 83

Answers (3)

heinst
heinst

Reputation: 8786

Here is how you would print out the list of lists columns.

lists = [[7, 6, 1, 8, 3],
[1, 7, 2, 4, 2],
[5, 6, 4, 2, 3],
[0, 3, 3, 1, 6],
[3, 5, 2, 14, 3],
[3, 11, 9, 1, 1],
[1, 10, 2, 3, 1]]

for i in range(0, len(lists[1])):
    for j in range(0, len(lists)):
        print lists[j][i],
    print "\n"

Upvotes: 0

Theodor Straube
Theodor Straube

Reputation: 193

Lists of lists

list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list in list_of_lists:
    for x in list:
        print x

Upvotes: 1

RomanK
RomanK

Reputation: 1266

Short answer:

for l in lists:
   print l[1]  

Upvotes: 4

Related Questions