-2

Im sure this is a repeated question, however I have no idea how to phrase it. What does pythons[1:3] yield?

pythons = [’Graham’, ’Eric’, ’Terry’, ’John’, ’Michael’, ’Terry’]

I know now the answer is Eric and Terry, but why?

K DawG
  • 12,572
  • 9
  • 32
  • 65
Justin
  • 647
  • 1
  • 9
  • 15

3 Answers3

5

Think about it like this:

    #0       #1       #2      #3        #4        #5
[’Graham’, ’Eric’, ’Terry’, ’John’, ’Michael’, ’Terry’]

As it was pointed out above, we start counting at 0 in python, and our ranges are not inclusive on the top end. So, when we say [1:3], we are saying "Grab all of the elements in this list from indexes in the range (1,3). So we split up the list like this

          |                 |    
    #0    |   #1       #2   |   #3        #4        #5
[’Graham’,| ’Eric’, ’Terry’,| ’John’, ’Michael’, ’Terry’]
          |                 |

So, a new list, ['Eric', 'Terry'] is returned. This same principle applies with strings too.

Alex Chumbley
  • 3,062
  • 7
  • 31
  • 58
1

List are ordered according to data entry, every time you append something this will be the last item of the list:

>>>pythons.append('Monty')
>>>pythons
['Graham', 'Eric', 'Terry', 'John', 'Michael', 'Terry', 'Monty']

indexes starts from 0 and you can imagine the index number between the elements:

['Graham', 'Eric', 'Terry', 'John', 'Michael', 'Terry', 'Monty']
0        1       2        3       4          5        6        

So pythons[1:3] select the elements between 1 and 3, Eric and the first Terry.

pythons[3] select the element that start from 3

Python Lists tutorial

Hrabal
  • 2,158
  • 2
  • 19
  • 28
0

pythons[1:3] yields Eric, Terry because

1 brings back the 2nd element in the list, because you start counting at 0. And 3 is the highest limit of the range, but is not inclusive so it brings back 2. That is why you get Eric, Terry.

Ramchandra Apte
  • 3,975
  • 2
  • 23
  • 43
CRABOLO
  • 8,495
  • 38
  • 39
  • 67