user1051003
user1051003

Reputation: 1231

How to loop through my 2d array?

I have an array which created with this:

numbers = []
for num in range(0,5): 
      nums = []
      for inum in range(0,5):
          nums.append(inum) 

      numbers.append(nums)

How to loop through? I tried for item in len(numbers): but it doesn't work.

Upvotes: 0

Views: 12746

Answers (4)

Haresh Shyara
Haresh Shyara

Reputation: 1886

Try to this.

[[col for col in range(5)] for row in range(5)]

Upvotes: 0

harvey
harvey

Reputation: 2953

List items are iterable, no need to get length as they will assign themselves to the first variable with for..in.. loops;

for item in numbers:
    print "In first list: ", item
    for num in item:
        print "    Getting number: ", num

outputs

In first list:  [0, 1, 2, 3, 4]
    Getting number:  0
    Getting number:  1
    Getting number:  2
    Getting number:  3
    Getting number:  4
In first list:  [0, 1, 2, 3, 4]
    Getting number:  0
    Getting number:  1
...

Upvotes: 4

Hai Vu
Hai Vu

Reputation: 40688

Double loop:

for row in numbers:
    for cell in row:
        print cell,
    print

Upvotes: 1

user4938503
user4938503

Reputation:

for i in range(5):
    for j in range(5):
        print numbers[i][j]

Upvotes: 1

Related Questions