Python - Slice Notation

> Procedural Languages > Python > Python - Data Type

1 - About

Slicing (sub-list) returns a list of elements in a sequence from the position a to the position before b.

Advertising

3 - Syntax

sequence[a:b:c]

where in the sequence[a:b:c]:

  • a is the first element of the slice. It can be negative (ie -2 means start from the last two elements of list)
  • b is the last element of the slice (not include)
  • c is the number of element to skip

4 - Example

4.1 - without skipping

my_list = [0, 1, 2, 3]
first_three_items = my_list[0:3]  # The first three items
first_three_items = my_list[:3]  # of 
last_two_items = my_list[len(my_list)-2:]  # will return the last two items
 
print my_list
# Prints [0, 1, 2, 3]
 
print first_three_items
# Prints [0, 1, 2]
 
print last_two_items
# Prints [2,3]

4.2 - With skipping

>>> my_list = [0, 1, 2, 3]
>>> my_list[::2]
[0, 2]
>>> my_list[1::2]
[1, 3]