Why does the list show the first two elements?

Asked

Viewed 125 times

1

Listing

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

when you show it, it comes like this

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

I believe you are 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 when 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 don’t understand, can someone explain to me?

2 answers

5


When you say

>>> convites[0:2]

is saying: from the 0 element of convites, go to the element preceding element 2.

He is not saying: take the element 0 and 2.

Ali is not a list but a continuous data range, you cannot select which elements you want, but where the desired track starts and ends. What comes before the two dots is where the track should start and what comes after is the element where it no longer belongs to the track. So in your example:

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

It started at 0 and went to 1 as 2 is the first to be excluded from what is intended.

  • An even better option for not having to set in hand is to use: invitations[:Len(invitations)] from 0 to the number of elements, since the index always starts at 0 the number of elements is always index+1.

5

The system of slices - Python slices work intuitively, and to this day the best way I have found to explain how it works is to make analogy with a ruler.

Imagine that you have a ruler, in centimeters, and put an item, like a shirt button, on each centimeter of the ruler: If you say "take the button at position 0" - it will take the button at the first centimeter of the ruler - between the number 0 and the number 1.

When you use the ":" 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 gets interesting because if you want to continue picking items on the same list, it continues on the number you left, and you don’t have to juggle subtraction (or add) 1 to the final item of the previous slice.

With a numerical list to be simpler you can see it 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]

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

How list assignment works using range?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.