Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit for loop to print first few element from list in python?

Tags:

python

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.

like image 840
Vivek Bhintade Avatar asked Nov 01 '13 06:11

Vivek Bhintade


People also ask

How do you print the first 5 elements of a list in Python?

To access the first n elements from a list, we can use the slicing syntax [ ] by passing a 0:n as an arguments to it . 0 is the start index (it is inculded).

How do you reduce iterations in Python?

Like this Python function, reduce() works by applying a two-argument function to the items of iterable in a loop from left to right, ultimately reducing iterable to a single cumulative value .

How do I limit a number in a list in Python?

Use the max() Function to Find Max Value in a List in Python. Python has a pre-defined function called max() that returns the maximum value in a list.

How do you loop through each item in a list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


1 Answers

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

like image 138
TerryA Avatar answered Nov 15 '22 11:11

TerryA