Python Program to Slice Lists
ⓘ Sponsored by 10xer.co
In Python, a slice is a portion of a list that is extracted using the colon (:) operator. The basic syntax of slice is as follows:
my_list[start:stop:step]
- start is the index of the starting element (inclusive).
- stop is the index of the stopping element (exclusive).
- step is the step size between elements.
Python Code :
The below Python program slices a list:
# Define a list of numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Slice the list to get the first three items
first_three = numbers[:3]
# Slice the list to get the last three items
last_three = numbers[-3:]
# Slice the list to get every other item
every_other = numbers[::2]
# Print the slices of the list
print("First three items:", first_three)
print("Last three items:", last_three)
print("Every other item:", every_other)
Output:
First three items: [1, 2, 3]
Last three items: [8, 9, 10]
Every other item: [1, 3, 5, 7, 9]
In this program, we first define a list of numbers called numbers.
We then use slice notation to create three new lists based on numbers.
- first_three is a slice of the first three items in numbers.
- last_three is a slice of the last three items in numbers.
- every_other is a slice of every other item in numbers.
- Finally, we print the slices of the list numbers.
Note that when using slice notation, the first index is inclusive and the last index is exclusive. This means that numbers[:3] will include the items at indices 0, 1, and 2, but not the item at index 3. Additionally, the third parameter in slice notation specifies the step size, which is why numbers[::2] returns every other item in the list.
ⓘ Sponsored by 10xer.co