-2

I want to return the number 5 from this:

list_1 = [[1, 2, 3], [4, 5, 6]]

I thought this would work but it is not:

print(list_1[1:1])

It returns an empty list. It is Index 1 (second list) and position 1 (second number in the list).

Shouldn't that work?

JD2775
  • 3,658
  • 7
  • 30
  • 52

4 Answers4

3

You need two separate operations:

sub_list = list_1[1]
item = sub_list[1]
# or shortly list_1[1][1]

What you did was calling the slice interface which has an interface of [from:to:step]. So it meant: "give me all the items from index 1 to index 1" (read about slicing for more information).

Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
2

list_1 = [[1, 2, 3], [4, 5, 6]]

then

list_1[0] == [1,2,3]
list_1[1] == [4,5,6]

then

list_1[1][1:1] == []  #slice starting from position '1', and around to the position before '1', effectively returning an empty list
list_1[1][1] == 5

edit corrections as from comments

1
list_1[1][1]

The first [1] gives you [4, 5, 6]. The next [1] gives you 5

Efe Esenwa
  • 40
  • 1
  • 1
  • 5
0

Let's say we have a list:

list_1 = [[1, 2, 3], [4, 5, 6]]

You're question asks, why does

list_1[1:1]

Return []?

Because you're asking for the objects from index 1 to index 1, which is nothing.

Take a simple list:

>>> x = [1, 2, 3]
>>> x[1:1]
[]

This is also empty because you're asking for all objects from index 1 to index 1.

All the 2nd number does is say the maximum reach non-inclusive. So...

>>> x = [1, 2, 3]
>>> x[1:10000]
[2, 3]
>>> x[1:-1023]
[]
>>> x[1:2]
[2]

If the 1st number is equal to or greater than the 2nd number, you'll always end up with an empty list unless you change the step of the slice (if it's equal, it'll always be empty)

Of a 2-dimensional array, if you wanted the 2nd object of the 2nd list in the list:

>>> list_1[1]
[4, 5, 6]
>>> list_1[1][1]
5
NinjaKitty
  • 638
  • 7
  • 17