Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over the first n elements of a list?

Tags:

python

list

slice

Say I've got a list and I want to iterate over the first n of them. What's the best way to write this in Python?

like image 402
Bialecki Avatar asked Apr 22 '10 03:04

Bialecki


People also ask

How do you find the first N elements of a list?

To access the first n elements from a list, we can use the slicing syntax [ ] by passing a 0:n as an arguments to it . 0 is the start index (it is inculded). n is end index (it is excluded).

How do you print the top 5 elements of a list in Python?

Method #1 : Using sorted() + lambda The combination of above functionality can be used to perform this particular task. In this, we just employ sorted function with reverse flag true, and print the top N elements using list slicing.


1 Answers

The normal way would be slicing:

for item in your_list[:n]:      ... 
like image 94
Mike Graham Avatar answered Oct 11 '22 12:10

Mike Graham