Reputation: 4615
I want to iterate a list but I want to iterate only first and second elements. For the edge case, if the list has only one or zero element, it should perform iterating one or zero time.
for element in a_list:
print(element)
Use Case
a_list = [] -> ''
a_list = ['a'] -> 'a'
a_list = ['a', 'b'] -> 'ab'
a_list = ['a', 'b', 'c'] -> 'ab'
a_list = ['a', 'b', 'c', 'd'] -> 'ab'
Upvotes: 0
Views: 1138
Reputation: 9010
You could create a function which yields the first two elements.
def yield_two(iterable):
it = iter(iterable)
yield next(it)
yield next(it)
With usage:
for e in yield_two('abcde'):
print(e) # 'a', 'b'
Upvotes: 0
Reputation: 87084
Using the Python 3 print()
function you can avoid explicit iteration and get the output in one statement:
>>> a_list = ['a', 'b', 'c', 'd']
>>> print(*a_list[:2], sep='')
ab
>>> a_list.pop()
>>> print(*a_list[:2], sep='')
ab
>>> a_list.pop()
>>> print(*a_list[:2], sep='')
ab
>>> a_list.pop()
>>> print(*a_list[:2], sep='')
a
>>> a_list.pop()
>>> print(*a_list[:2], sep='')
This slices a_list
, unpacks the elements of the slice, and prints them using an empty string as the separator.
You can use the same function in Python 2 by adding this to the top of your script:
from __future__ import print_function
Upvotes: 0
Reputation: 4420
If you want to output 2 elements then use:-
for element in a_list[:2]:
print(element)
If you want to output 2 elements like a string just explained in the question use:-
"".join(a_list[:2])
Upvotes: 1