I can't make sense of this code:

+1 vote
asked Sep 12, 2017 by hagogs

I am trying to get into working with 2 dimensional lists/tuples because I want to use them for an idea I have. I have always had trouble understanding the for instruction, it just doesn't make any sense to me, it doesn't feel intuitive. The problem is that I just don't understand the for instruction. I got this code that displays this simple tuple:

m=((1,2),(3,4),(5,6))

for i in range(len(m)):
    for j in range(len(m[i])):
        print(m[i][j]," ",end="")
        print()

This displays:

1 2
3 4
5 6

I don't really get what this parts of the code mean (m[i]) and m[i][j] I know what len is for.

Also I tried to change the [] to () because they are supposed to be part of a tuple but I get an error that says:

TypeError occurred Message='tuple' object is not callable

If I remove parts of the code the result is displayed with parenthesis, but this code somehow removes all the parentheses from the tuple:

m=((1,2),(3,4),(5,6))

for i in range(len(m)):

    print(m[i])
    print()

For example this one displays basically the same result but with the parentheses:

(1,2)
(3,4)
(5,6)

What is going on here?

EDIT:

BELOW IN THE ANSWERS I WROTE THE CODE THAT HELPED ME UNDERSTAND EVERYTHING I WASN'T UNDERSTANDING AND EXPLAINED IT, THANKS FOR ALL YOUR ANSWERS WOULDN'T BEEN ABLE TO DO THAT WITHOUT YOUR INPUT.

5 Answers

0 votes
answered Sep 12, 2017 by phydeaux

[] is the subscript operator. m[0] returns the 0'th element of m, which is (1,2).

Similarly, m[0][0] returns 1.

This operator is the same for any collections, no matter if it is a list [...], tuple (...) or set {...}. m(i) is trying to call m like a function, which is not allowed by a tuple.

+3 votes
answered Sep 12, 2017 by christian-dean

The outer for loop iterates through each tuple in m index-wise:

>>> m = ((1,2),(3,4),(5,6))
>>> for i in range(len(m)):
        print(m[i])


(1, 2)
(3, 4)
(5, 6)

The inner (nested) for loop iterates through each tuple accsed by m[i], also index-wise, and print's it's content all on one line:

>>> m = ((1,2),(3,4),(5,6))
>>> # loop through each tuple in `m` index-wise
>>> for i in range(len(m)):
    # loop through each element in each tuple index-wise
        for j in range(len(m[i])):
        # print each element on a single line.
            print(m[i][j]," ",end="")
        # print a newline
        print()


1  2  
3  4  
5  6  

The reason this feels so awkward is because you're not using for-loops the way they were designed to be used, i.e idiomatically. Python for-loops are made to iterate over collections element-wise, not index-wise. There's no need to use range or len at all. Iterate directly over m, and each tuple in m:

for tup in m:
    for num in tup:
        print(num," ",end="")
    print()

As you can see, the above is much cleaner to write and understand.

0 votes
answered Sep 12, 2017 by edw

How to initialize 2d arrays and tuples:

myarr = [[1, 2], [3, 4]] # A 2d array mytuple = ((5, 6), (7, 8)) # A 2d tuple

How to access 2d lists:

print(myarr[0]) # = [1, 2] print(myarr[1][0]) #get the 1st element of the second array in myarr = 3

You access 2d tuples the same way:

print(mytuple[0]) # = (5, 6) print(mytuple[1][0]) #get the 1st element of the second tuple in myarr = 7

Doing mytuple(1) is trying to call function 'mytuple', which obviously is a tuple and not a function, so there is an error.

0 votes
answered Sep 12, 2017 by fady-saad

First of all I will remove your confusion by clarify the different between tuple and List, how to access both of them:

First List: also called sequence, Each element of a sequence is assigned a number - its position or index. The first index is zero, the second index is one, and so forth

And for accessing it's elements you should use [index] with the index(position of the element you want to get)

Second Tuple: a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

And for accessing it's values you also use [index] with the index(position of the element you want to get)

And your code is valid for both list and tuple:

 m = ((1,2),(3,4),(5,6))
 #loop through each tuple in `m` 
 for i in range(len(m)):
    #loop through each element in each tuple 
        for j in range(len(m[i])):
        #print each element on a single line.
            print(m[i][j]," ",end="")
        #print a newline
        print()
0 votes
answered Sep 12, 2017 by hagogs

Based on all the information i got from you guys i wrote this:

m=((1,2),(3,4),(5,6))


for i in range(len(m)):
    for j in range(len(m[i])):
        print(m[i][j]," ",end="")
    print()

print()
print(len(m))
print(len(m[i]))
print()

for tup in m:
    for elem in tup:
        print(elem, end=' ')
    print()

print()
print()

for tup2 in m:
    for num in tup2:
        print(num," ",end="")
    print()

print()
print()
print("333",end=" ")
print("4444",end=" ")
print("55555")

What was confusing me was that i didn't knew what were the values of "i" and "j" and then on top of that what the print was doing also was adding to this confusion, so i just printed the values of "i" and "j" and they were 3 and 2 and then after making sense of what the print was doing i got it.

-First is doing 3 loops, and 3 is from the len of the tuple

-After that it is doing 2 loops based on the len of the other 3 tuples which is 2

-Finally it is printing each element like this m[i][j] which means it will start with the element 0,0 then 0,1, then 1,0, then 1,1 then 2,0, then 2,1

This would be the "map" of the tuple:

(0,0) (0,1)

(1,0) (1,1)

(2,0) (2,1)

Each element has it's coordinates first element is 0,0 the second is 0,1 and so on.

And for this to be printed like this and not in a single line you use:

 print(m[i][j]," ",end="")
print()

What i understood about this was that " " is just an space, no matter, but end"") is making so the code doesn't break the line thus prints each loop on a single line and ends each line it prints with an space so it doesn't print the result one after the other, the other print() just adds a break line to make it more "readable".

All i got thanks to you guys because i was not seeing this before, why i got the error, why i wasn't understanding the for loops, why i could have done it in a simpler way.

Everything is clear now guys, thank you all.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter

...