pythonic way to iterate over part of a list

前端 未结 7 1840
日久生厌
日久生厌 2020-12-08 08:55

I want to iterate over everything in a list except the first few elements, e.g.:

for line in lines[2:]:
    foo(line)

This is concise, but

7条回答
  •  攒了一身酷
    2020-12-08 09:37

    The original solution is, in most cases, the appropriate one.

    for line in lines[2:]:
        foo(line)
    

    While this does copy the list, it is only a shallow copy, and is quite quick. Don't worry about optimizing until you have profiled the code and found this to be a bottleneck.

提交回复
热议问题