0

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'
Rachit kapadia
  • 705
  • 7
  • 18
merry-go-round
  • 4,533
  • 10
  • 54
  • 102
  • 5
    Possible duplicate of [Understanding Python's slice notation](https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation) – awesoon Dec 19 '17 at 04:48

4 Answers4

3
for element in a_list[:2]:
    print(element)
Xero Smith
  • 1,968
  • 1
  • 14
  • 19
1

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])
Rakesh Kumar
  • 4,319
  • 2
  • 17
  • 30
0

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
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

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'
Jared Goguen
  • 8,772
  • 2
  • 18
  • 36