Return the first 5 items from a Python list

Asked

Viewed 406 times

-1

Given the list below:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Is there a quick way to get the top 5 items on this list? Something like list.get_first(5)?

  • I did not quite understand the purpose of the question, but in my view the proposal is exactly the same as the one I put as duplicate. If you disagree, please comment arguing the differences and I’ll reassess the closure.

  • I read the duplicate that scored and really answers the question, even though I find the answer a little confused and less succinct.

1 answer

1


According to this tutorial from the Python documentation, you can use the "slicing" functionality of the lists, making:

first_5 = array[:5]

That will return to the following list:

[1, 2, 3, 4, 5]

You can also use the contents of the list, following the syntax:

array[start:stop:step]

To illustrate, we can take the number 2 to the 10 by jumping from 2 to 2 (including the 2 and excluding the 10) doing:

list[1:9:2]

Which would result in:

[2, 4, 6, 8]

Browser other questions tagged

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