1

for this list ,

l=[i for i in range(1,100)]

How can i restrict to print only 1st 20 elements.

What i am trying to do is ,

>>> counter=0
>>> for index , i in enumerate(l):
...    if counter==20:
...        break
...    print index , i
...    counter+=1
...

Is there is another way to do this without using counter variable ?

2 Answers 2

4

Use a sliced list, like this

l=[i for i in range(1,100)]
for index, i in enumerate(l[:20]):
    print index, i

Or you can use itertools.islice, to avoid generating entire list and instead iterate over xrange as long as you want, like this

from itertools import islice
for index, i in enumerate(islice(xrange(1, 100), 20)):
    print index, i
Sign up to request clarification or add additional context in comments.

Comments

1

Nishant N.'s answer is the probably the best. But your code would also have worked had you changed your if statement to read

if i == 20:

Just in case you wondered why it wasn't working (also you would have needed to set counter to 0 before the code you posted, but I accept that may just have been omitted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.