-1

For the following:

list=[[2, 3, 5], [7, 8, 9]]

Why does [list[0][0], list[1][0]] represent the first row ([2, 7]), but the command list[:][0] or list[0:2][0] returns the first column ([2, 3, 5])?

The way I see it list[:][0] should get all the possible values for the first parameter (that is 0 and 1) and 0 for the second, meaning it would return the first row. Instead what it does is return the first column and I can't understand why.

4castle
  • 32,613
  • 11
  • 69
  • 106
Victor
  • 23
  • 1
  • 6

1 Answers1

1

In python, the [a:b:c] syntax creates a new list. That is,

list = [1,2,3]
print(list[:])

is going to print a list, not a value.

Therefore, when you say list[:][0] you are making a copy of the original list (list[:]) and then accessing item 0 within it.

Of course you know, item 0 of the original list (list[0]) is another list.

I think you want:

[sl[0] for sl in list]

Elaboration:

This is called a "comprehension." It is a compact special syntax for generating lists, dicts, and tuples by processing or filtering other iterables. Basically {..}, [..], and (..) with an expression inside involving a for and optionally an if. Naturally, you can have multiples (like [x for x in y for y in z]) of the for, and multiples of the if.

In your case, it's pretty obvious you want a list. So []. You want to make the list by taking the first item from each sublist. So [sl[0] for sl in list].

Here's a more-detailed article: http://carlgroner.me/Python/2011/11/09/An-Introduction-to-List-Comprehensions-in-Python.html

aghast
  • 14,785
  • 3
  • 24
  • 56
  • I understand the explanation and the solution you gave works! I just don`t understand the syntax. Could you elaborate a little bit? Thanks! – Victor Feb 11 '17 at 02:38