merry-go-round
merry-go-round

Reputation: 4615

Iterate ONLY first and second list python

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

Upvotes: 0

Views: 1138

Answers (4)

Jared Goguen
Jared Goguen

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

mhawke
mhawke

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

Rakesh Kumar
Rakesh Kumar

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

Xero Smith
Xero Smith

Reputation: 2076

for element in a_list[:2]:
    print(element)

Upvotes: 3

Related Questions