Slicing

my_list = [1, 2, 3, 4, 5]

# Get the first three elements of the list
first_three = my_list[:3]
print(first_three)  # output: [1, 2, 3]

# Get the last two elements of the list
last_two = my_list[-2:]
print(last_two)  # output: [4, 5]

# Get every other element of the list
every_other = my_list[::2]
print(every_other)  # output: [1, 3, 5]

all of the above examples are valid code.

Last updated