Accessing a set of elements within a list

It is possible to access elements between specified indices. For example, it is possible to retrieve all elements between indices 2 and 4:

    >>> random_list[2:5]    [5, 7, 5]

The first six elements of a list could be accessed as follows:

    >>> random_list[:6]    [4, 6, 5, 7, 5, 2]

The elements of a list could be printed in the reverse order as follows:

    >>> random_list[::-1]    [8, 7, 5, 2, 2, 5, 7, 5, 6, 4]

Every second element in the list could be fetched as follows:

    >>> random_list[::2]    [4, 5, 5, 2, 7]

It is also possible to fetch every second element after the second element after skipping the first two elements:

    >>> random_list[2::2]    [5, 5, 2, 7]

Get Python Programming with Raspberry Pi now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.