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.
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).
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 .
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.
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.
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 :).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With