I think this would be considered pythonic:
for item in a[:3]:
print item
Edit: since a matter of seconds made this answer redundant, I will try to provide some background information:
Array slicing allows for quick selection in sequences like Lists of Strings. A subsequence of a one-dimensional sequence can be specified by the indices of left and right endpoints:
>>> [1,2,3,4,5][:3] # every item with an index position < 3
[1, 2, 3]
>>> [1,2,3,4,5][3:] # every item with an index position >= 3
[4, 5]
>>> [1,2,3,4,5][2:3] # every item with an index position within the interval [2,3)
[3]
Note that the left endpoint is included, the right one is not. You can add a third argument to select only every n
th element of a sequence:
>>> [1,2,3,4,5][::2] # select every second item from list
[1, 3, 5]
>>> [1,2,3,4,5][::-1] # select every single item in reverse order
[5,4,3,2,1]
>>> [1,2,3,4,5][1:4:2] # every second item from subsequence [1,4) = [2,3,4]
[2, 4]
By converting lists to numpy arrays, it is even possible to perform multi-dimensional slicing:
>>> numpy.array([[1,2,3,4,5], [1,2,3,4,5]])[:, ::2]
array([[1, 3, 5],
[1, 3, 5]])