1

I'm having trouble understanding the syntax here.

matrix_a = [[1, 2], [3, 4], [5, 6]]
matrix_b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

[a for a, b in matrix_a]

output: [1, 3, 5]

[a for b, a in matrix_a] 

output: [2, 4, 6]

I understand a little about how list-comprehensions work, but I don't understand the syntax when accessing certain elements within a nested list.

I just can't wrap my head around this syntax. How is this syntax working? What does the comma represent? What does a for a mean? Can you explain whats going on under the hood? And finally how would you do this with matrix_b

hynekcer
  • 14,942
  • 6
  • 61
  • 99
  • The question listed as a duplicate is about nested list comprehensions, this question is not about that. – thebjorn Nov 08 '17 at 09:28

3 Answers3

3

If you convert it to a for loop it might be easier to see..?

res = []
for item in matrix_a:
    a, b = item   # a = item[0]; b = item[1]
    res.append(a)

you're basically unpacking the individual items in the list and picking one of them.

thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

I think you have mistaken in writing output here [a for a, b in matrix_a] returns [1 2 4] which is logical , returning first element of each nested list item

see the Outputscreenshot

Ranjeet Singh
  • 159
  • 10
  • You could have copied the text instead of using an image. Also, this doesn't seem like an _answer_ ..? – thebjorn Nov 08 '17 at 09:33
0

just understand in this way:

[a for b, a in matrix_a]  #as
[a for [a, b] in matrix_a] #or
[a for (a, b) in matrix_a]
#matrix_a has elements as list of length 2 each
#so your list comprehenssion says, give me a output list -- having first element'a' from each element of matrix_a(whose each element represented as [a,b] type, with comma, becomes tuple (a,b)),
# then from [b,a] give me a, that is 2nd element
# and it will fail if you apply same on matrix_b, cause each element of matrix_b is not of type [a,b] i:e of length 2
# you will get "ValueError: too many values to unpack"

Let me know if anything is not clear. Thanks.

Satya
  • 5,470
  • 17
  • 47
  • 72