These advertisements helps me to keep writing articles on this website

Python list slicing

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.

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 January 15, 2021. Questions regarding this artice? You can send them to the address below.
By using this site, you acknowledge that you have read and understand our Cookie and Privacy Policy.