7

How should i print the first 5 element from list using for loop in python. i created some thing is here.

x= ['a','b','c','d','e','f','g','h','i']
for x in x:
   print x;

with this it just print all elements within list.but i wanted to print first 5 element from list.thanks in advance.

1 Answer 1

22

You can use slicing:

for i in x[:5]:
    print i

This will get the first five elements of a list, which you then iterate through and print each item.

It's also not recommended to do for x in x:, as you have just overwritten the list itself.

Finally, semi-colons aren't needed in python :).

Sign up to request clarification or add additional context in comments.

8 Comments

And this won't raise any IndexError if list contains fewer items.
Alternatively - for much larger slices than 5 elements - use itertools.islice to avoid constructing a large temporary sublist. But it doesn't matter in this case.
@PeterDeGlopper Slicing is faster than islice in almost all cases.
Actully what i wanted know is. I read the records from mongodb in one variable with test = collectionname.fetch() and i wanted to print first few records from this all records in html did like {{ %for i in test }} //perform other operation on i so instead of this way is there any other way With this loop operation is performed on all records.
@hcwhsa - thanks for the link, I'll have to remember that. I guess islice is mostly better for slicing non-list iterables like other generator expressions.
|

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.