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

谁都会走 提交于 2019-11-30 00:18:59

The normal way would be slicing:

for item in your_list[:n]: 
    ...

I'd probably use itertools.islice (<- follow the link for the docs), which has the benefit of working with any iterable object.

ezod

You can just slice the list:

>>> l = [1, 2, 3, 4, 5]
>>> n = 3
>>> l[:n]
[1, 2, 3]

and then iterate on the slice as with any iterable.

Python lists are O(1) random access, so just:

for i in xrange(n):
    print list[i]
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!