Reputation: 383
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.
Upvotes: 7
Views: 25136
Reputation: 59974
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 :).
Upvotes: 22