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

后端 未结 4 561
悲哀的现实
悲哀的现实 2020-12-08 06:09

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?

相关标签:
4条回答
  • 2020-12-08 06:47

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

    for i in xrange(n):
        print list[i]
    
    0 讨论(0)
  • 2020-12-08 06:52

    The normal way would be slicing:

    for item in your_list[:n]: 
        ...
    
    0 讨论(0)
  • 2020-12-08 06:53

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

    0 讨论(0)
  • 2020-12-08 06:54

    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.

    0 讨论(0)
提交回复
热议问题