-1

I'm trying to figure out why this doesn't return the 3rd element.

Input:
t = [(3,300),(1,100),(2,200),(4,400),(5,500)]
t.sort()
print(t)
t = t[0:2]
print(t)

Output:
[(1, 100), (2, 200), (3, 300), (4, 400), (5, 500)]
[(1, 100), (2, 200)]

Thanks! And sorry for the simple question. I would have expected the result to be: [(1, 100), (2, 200),(3,300)]

keynesiancross
  • 3,441
  • 15
  • 47
  • 87
  • 5
    Because `a[i:j]` is `i` **included** and `j` **excluded**. That is *slice notation*. – Willem Van Onsem Feb 21 '17 at 17:58
  • 3
    Possible duplicate of [Explain Python's slice notation](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) – Prune Feb 21 '17 at 18:02
  • Your first instinct here should be to [check the documentation](https://docs.python.org/3.5/library/stdtypes.html#common-sequence-operations)... not post a question. – juanpa.arrivillaga Feb 21 '17 at 18:07

2 Answers2

1

The notation is like this A[a:b] where A is an array, a is the start point (zero indexed and an integer), and b is the stop point (also an integer and zero indexed). The last element in the selection, IE the one found at the stop point, is not captured so if the stop point is the same as the start point, no elements are captured.

So if I have A=[0,1,2,3] and type A[0:0] I get []. But If I type A[0:1] I get [0]. Note that A[:1] is the same as A[0:1] is the same as [A[1]]. If you just want the first 3 elements, try A[:3].

What's happening?

Underneath, when you call object[a:b:c] it is interpreted as object.__getitem__( slice(a, b, c) ). Note that the slice class has the following instantiation call: slice(start, stop, step). This allows it to skip over elements or reverse order if you give it a negative step and switch the start and stop. So A[slice(None,None,-1)] is the same as A[::-1] which selects the entire array by iterating through it backwards, thus returning the entire list in reverse order. For more on slice notation see: Explain Python's slice notation

amoose136
  • 178
  • 1
  • 8
0

Python indices start from 0, so if you need the first three you would need the items at t[0], t[1] and t[2]. you should do as follows.

t = [(3,300),(1,100),(2,200),(4,400),(5,500)]
t.sort()
print(t)
t = t[0:3]
print(t)
Yonas Kassa
  • 3,362
  • 1
  • 18
  • 27