Why does the list show the first two elements?

1

Declaring a list

>>> convites = ['Flavio Almeida', 'Nico Steppat', 'Romulo Henrique']

When it shows, it appears like this

>>> convites[0]
'Flavio Almeida'
>>> convites[1]
'Nico Steppat'
>>> convites[2]
'Romulo Henrique'

I believe it is correct, because of this;

posição           0                 1                2
>>> convites = ['Flavio Almeida', 'Nico Steppat', 'Romulo Henrique']

Because Flavio is in position 0, Nico is in position 1 and Romulo in position 2

Because at the time of printing two positions it behaves differently, as shown below?

>>> convites[0:2]
['Flavio Henrique', 'Nico Steppat']

In my opinion it should be

['Flavio Henrique', 'Romulo Henrique']

I do not understand, can anyone explain?

    
asked by anonymous 19.02.2016 / 11:26

2 answers

4

When it says

>>> convites[0:2]

You are saying: from element 0 of convites , go to the element that precedes element 2.

It's not saying: get element 0 and 2.

There is not a list but a continuous data band, you can not select which elements you want and yes where starts and ends the desired track. What comes before the colon is where the track should start and what comes next is the element where it no longer belongs to the track. Then in your example:

posição           0                 1                2
>>> convites = ['Flavio Almeida', 'Nico Steppat', 'Romulo Henrique']

It started at 0 and was up to 1 since 2 is the first to be excluded from what is intended.

    
19.02.2016 / 11:32
5

The slices - Python slices system works intuitively, and to this day the best way I've found to explain how it works is to make analogy with a rule.

Imagine you have a ruler in centimeters and place an item like a shirt button on each centimeter of the ruler: If you say "get the button in position 0" - it will pick up the button that is on the first centimeter of the rule - between the number 0 and the number 1.

When you use ":" to create a slice, that's what you're saying, with [0:2] : get me the items from position "0 to position 2."

Note that it is interesting because if you want to continue picking up items from the same list, continue with the number where you left off, and you do not have to juggle subtracting (or adding) 1 to the last item in the previous slice. >

With a numerical list to get simpler you can see that well.

>>> a = list(range(10, 20))
>>> a
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
>>> a[0:3]
[10, 11, 12]
>>> a[3:6]
[13, 14, 15]
>>> a[6:9]
[16, 17, 18]
>>> a[9:]
[19]

After you understand this part, take a look at another answer from me where I analyze more advanced aspects of the slice system used in Python:

How does list assignment work using range?

    
21.02.2016 / 04:09