Python: What does for x in A[1:] mean?

Python: What does for x in A[1:] mean?

Here are some of the example that I have tried

>>> a=[1,5,9,11,2,66]

>>> a[1:]
[5, 9, 11, 2, 66]

>>> a[:1]
[1]

>>> a[-1:]
[66]

>>> a[:-1]
[1, 5, 9, 11, 2]

>>> a[3]
11

>>> a[3:]
[11, 2, 66]

>>> a[:3]
[1, 5, 9]

>>> a[-3:]
[11, 2, 66]

>>> a[:-3]
[1, 5, 9]

>>> a[::1]
[1, 5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[1::]
[5, 9, 11, 2, 66]

>>> a[::-1]
[66, 2, 11, 9, 5, 1]

>>> a[::-2]
[66, 11, 5]

>>> a[2::]
[9, 11, 2, 66]

I think you can understand more by this examples.

This is array slice syntax. See this SO question:
Explain Pythons slice notation .

For a list my_list of objects e.g. [1, 2, foo, bar], my_list[1:] is equivalent to a shallow copied list of all elements starting from the 0-indexed 1: [2, foo, bar]. So your for statement iterates over these objects:

for-iteration 0: x == 2 
for-iteration 1: x == foo 
for-iteration 2: x == bar 

range(..) returns a list/generator of indices (integers), so your for statement would iterate over integers [1, 2, ..., len(my_list)]

for-iteration 0: x == 1 
for-iteration 1: x == 2
for-iteration 2: x == 3

So in this latter version you could use x as an index into the list: iter_obj = my_list[x].

Alternatively, a slightly more pythonic version if you still need the iteration index (e.g. for the count of the current object), you could use enumerate:

for (i, x) in enumerate(my_list[1:]):
    # i is the 0-based index into the truncated list [0, 1, 2]
    # x is the current object from the truncated list [2, foo, bar]

This version is a bit more future proof if you decide to change the type of my_list to something else, in that it does not rely on implementation detail of 0-based indexing, and is therefore more likely to work with other iterable types that support slice syntax.

Python: What does for x in A[1:] mean?

Unlike other languages, iterating over a sequence in Python yields the elements within the sequence itself. This means that iterating over [1, 2, 4] yields 1, 2, and 4 in turn, and not 0, 1, and 2.

Leave a Reply

Your email address will not be published.