Four common list operations are first, take, skip and last, also known as head, tail, init and last. Here is a picture that shows how to perform these operations in Python.

Python list slicing.

slicing

Head or First

wagons = [0, 1, 2, 3, 4]
wagons[0]  # 0 (single item)
wagons[:1] # [0] (list with item 0)

Tail or Skip

wagons = [0, 1, 2, 3, 4]
wagons[1:] # [1, 2, 3, 4] (list)

Init or Take

wagons = [0, 1, 2, 3, 4]
wagons[:-1] # [0, 1, 2, 3] (list)

Last

wagons = [0, 1, 2, 3, 4]
wagons[-1]  # 4 (single item)
wagons[-1:] # [4] (list with item 4)
Written by Loek van den Ouweland on 2021-01-15.
Questions regarding this artice? You can send them to the address below.