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.

Sam Dufel
  • 17,560
  • 3
  • 48
  • 51
Vivek Bhintade
  • 373
  • 2
  • 4
  • 11

1 Answers1

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 :).

TerryA
  • 58,805
  • 11
  • 114
  • 143
  • 2
    And this won't raise any `IndexError` if list contains fewer items. – Ashwini Chaudhary Nov 01 '13 at 06:53
  • 1
    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. – Peter DeGlopper Nov 01 '13 at 06:54
  • 2
    @PeterDeGlopper [Slicing is faster than `islice`](http://stackoverflow.com/questions/18048698/efficient-iteration-over-slice-in-python) in almost all cases. – Ashwini Chaudhary Nov 01 '13 at 06:55
  • 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. – Vivek Bhintade Nov 01 '13 at 06:56
  • @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. – Peter DeGlopper Nov 01 '13 at 06:59
  • @VivekBhintade I'm not familiar with that type of syntax, sorry – TerryA Nov 01 '13 at 07:01
  • @VivekBhintade If you're using django, then django templates also support slicing: https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#slice – Ashwini Chaudhary Nov 01 '13 at 07:01
  • @VivekBhintade - can you add more detail regarding exactly what your data source is to your question? The slicing answer is correct for lists, which is what your question currently refers to. – Peter DeGlopper Nov 01 '13 at 07:06