Python List – Indexing and Slicing


List Indexing

As a Python list is an ordered sequence, each item is assigned the index position starting with 0. We can access each item by passing the index position in the square brackets.

Example:

emp_details = [‘Brad’,’Lee’,’Sales’,380,250000,True,’New York’,’USA’,’Developer’,’Python’]

Index Positions:

Python List - Indexing and Slicing

Let us understand with some examples:

In [1]:
emp_details = ['Brad','Lee','Sales',380,250000,True]

Check what is at position 0.

In [2]:
print(emp_details[0])
Brad

Position 4.

In [3]:
print(emp_details[4])
250000

List Slicing

The slicing operation can extract a list of two or more than two items from the list. While performing slicing, we can pass three optional parameters in the square brackets separated by a colon.

List[StartPosition : EndPosition : Step]

StartPosition Item at which we want to start. Default is the first character.
EndPosition Up to which item we want to go(Note: this is up to, the item at this specific location will not be included). Default is the last last.
Step The number of steps we want to it to take. By default, it is 1, means it will take one step at a time.

When we don’t use a colon(:) then the argument is considered as the position of an item.

Let us understand index positions with some examples:

Only using start to end.

In [1]:
emp_details = ['Brad','Lee','Sales',380,250000,True,'New York','USA','Developer','Python']
print(emp_details[0:])
['Brad', 'Lee', 'Sales', 380, 250000, True, 'New York', 'USA', 'Developer', 'Python']

Start with 3 to end.

In [2]:
print(emp_details[3:])
[380, 250000, True, 'New York', 'USA', 'Developer', 'Python']

Go up to 3. Note: Item at position 3 will not be included.

In [3]:
print(emp_details[:3])
['Brad', 'Lee', 'Sales']

Include all with step of 2.

In [4]:
print(emp_details[::2])
['Brad', 'Sales', 250000, 'New York', 'Developer']

Start at 2 up to 8.

In [5]:
print(emp_details[2:8])
['Sales', 380, 250000, True, 'New York', 'USA']

Start with 1 up to 8 with step of 3.

In [6]:
print(emp_details[1:8:3])
['Lee', 250000, 'USA']

Negative Indexing

We can also use negative indexing. The last item is assigned with the index position of -1. It keeps on increasing in the negative order until the first item. If we want to traverse backward, we can use jump as a negative number. Example -1.

Example:

emp_details = [‘Brad’,’Lee’,’Sales’,380,250000,True,’New York’,’USA’,’Developer’,’Python’]

Negative Index Positions:

Negative Index Positions:

Let us understand with some examples:

Item at -2 position.

In [1]:
emp_details = ['Brad','Lee','Sales',380,250000,True,'New York','USA','Developer','Python']
print(emp_details[-2])
Developer

This will not work because the default jump size is 1 which is positive but to traverse backward we need a negative jump size.

In [2]:
print(emp_details[-2:-6])
[]

Traversing from -2 uptill -6 with jump of -1.

In [3]:
print(emp_details[-2:-6:-1])
['Developer', 'USA', 'New York', True]

Traversing from -5 to -2 with a positive jump i.e. default 1.

In [4]:
print(emp_details[-5:-2])
[True, 'New York', 'USA']

We can use this approach to reverse the list.

In [5]:
print(emp_details[::-1])
['Python', 'Developer', 'USA', 'New York', True, 250000, 380, 'Sales', 'Lee', 'Brad']

Check if an item exists in List

To check whether an item exists inside the list or not, we use the membership operator in.

In [1]:
emp_details = ['Brad','Lee','Sales',380,250000,True]
if ("Brad" in emp_details):
    print("Welcome, Brad!")
Welcome, Brad!

As Steve is not present, so nothing gets printed.

In [2]:
emp_details = ['Brad','Lee','Sales',380,250000,True]
if ("Steve" in emp_details):
    print("Welcome, Steve!")  

Index out of range error

If we try to access any index position where no item is present, then we get ‘index out of range’ error.

If we try to access item at index 2, we get index out of range error.

In [1]:
emp_details = ['Brad','Lee']
print(emp_details[2])
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-1-bde5aa4163cd> in <module>
      1 emp_details = ['Brad','Lee']
----> 2 print(emp_details[2])

IndexError: list index out of range

References

  1. Python List (With Examples)
  2. Python Program to Slice Lists
  3. Slicing and Indexing in Python – Explained with Examples