Gillesbert
Gillesbert

Reputation: 23

How to limit for loop to print first few element from list in terms of their value in python?

I would like to limit for loop to print first few element from list in terms of their value. For example, if i < 6 :

list = [1,2,3,4,5,6,7,8,9,10]
for i < 6 in list:
    print(i)

Thanks in advance !

Upvotes: 2

Views: 159

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180401

based on I would like to limit for loop to print first few element from list in terms of their value it seems the list is in order so you can use itertools.takewhile :

from itertools import takewhile

lst = [1,2,3,4,5,6,7,8,9,10] # don't use list

tke = takewhile(lambda x: x< 6, lst)

for t in tke:
    print(t)
1
2
3
4
5

If you want a list use list(...).

print(list(takewhile(lambda x: x< 6, lst))) # good reason why we should not use list as a variable name 
[1, 2, 3, 4, 5]

Upvotes: 0

inspectorG4dget
inspectorG4dget

Reputation: 113945

In [9]: L = [1,2,3,4,5,6,7,8,9,10]

In [10]: for i in L:
   ....:     if i<6:
   ....:         print(i)
   ....:         
1
2
3
4
5

Upvotes: 1

Related Questions