Python Program - Slice Lists

ht‮www//:spt‬.theitroad.com

To slice a list in Python, you can use the slicing operator :. The syntax for slicing a list is as follows:

new_list = old_list[start:end:step]

where:

  • old_list: The original list to be sliced
  • start: The starting index of the slice (inclusive)
  • end: The ending index of the slice (exclusive)
  • step: The step value between each element in the slice (default is 1)

Here are some examples:

# create a list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# slice the list to get elements 2, 3, 4
slice1 = my_list[1:4]
print(slice1)   # Output: [2, 3, 4]

# slice the list to get elements 1, 3, 5, 7
slice2 = my_list[0:8:2]
print(slice2)   # Output: [1, 3, 5, 7]

# slice the list to get the last 3 elements
slice3 = my_list[-3:]
print(slice3)   # Output: [7, 8, 9]

Note that the start and step arguments are optional. If you omit start, it defaults to 0. If you omit step, it defaults to 1.