That's not what this expression does. lista[inicio:fim]
creates a sublist started (inclusive) in inicio
and ends (exclusively) in fim
:
>>> [0,1,2,3,4,5][1:4]
[1, 2, 3]
>>> [0,1,2][0:3]
[0, 1, 2]
Note that in this second example the list was the same (since you started at the beginning and it was until its end. Similarly, in your code the sublist returned is the same as the original array, and when you access your second element you're actually picking up the second line:
>>> matriz = [[1,5],
... [7,4],
... [8,3]]
>>> matriz[0:3]
[[1, 5], [7, 4], [8, 3]]
>>> matriz[0:3][1]
[7, 4]
If you want the second element of each row in the array, you can use an understanding of lists:
>>> [x[1] for x in matriz]
[5, 4, 3]
Then just add a loop to print them one by one:
>>> for v in [x[1] for x in matriz]:
... print v
...
5
4
3
(although in this case it's bullshit to do this, it would be enough to iterate over the original list and print v[1]
...)
By the way, if instead of a list you have an object, you can use other complex objects (such as tuples) as keys. In this case it would make sense to matriz[0, 1]
, but it would be accessing a specific property of the object and not two distinct values of a nested list:
>>> x = []
>>> x[1, 2] = 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not tuple
>>> x = {}
>>> x[1, 2] = 10
>>> x
{(1, 2): 10}
But if what you have are lists of lists, in fact you need two uses of the brackets to access an internal element, you can not (unfortunately ...) use tuples as indexes.
Note: If is extremely , you could put print
inside the list itself by avoiding a loop. In Python 3 at least, I do not know if you can do this in Python 2:
>>> [print(x[1]) for x in matriz]
5
4
3
[None, None, None]
(this last line is the created list, where each element is the return of print
- None
, usually it will be ignored)
Just be careful that this creates a new list, the same size as the original (1st level), which raises memory consumption. This technique would only be recommended if you were in a context where only one expression (within a lambda
, for example) is fit, and - by conciseness - you want to avoid creating a new function.