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?
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?
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.
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
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
.