Junior
What are slices in Python and how are they used?
sobes.tech AI
Answer from AI
Slices in Python are a convenient way to obtain subsequences from ordered collections such as strings, lists, and tuples. They allow extracting elements or parts of a sequence without modifying the original collection.
Slice syntax: [start:stop:step]
start: The starting index of the slice (inclusive). Default is 0.stop: The ending index of the slice (exclusive). Default is the end of the sequence.step: The step of the slice (how many elements to skip). Default is 1.
Indices can be negative. A negative index counts from the end of the sequence (-1 is the last element, -2 is the second last, etc.).
Examples of usage:
# String
s = "Hello, world!"
# Slice from the beginning to the 5th element (excluding)
print(s[:5]) # Output: Hello
# Slice from the 7th element to the end
print(s[7:]) # Output: world!
# Slice from the 7th to the 12th element (excluding)
print(s[7:12]) # Output: world
# Copying the string
print(s[:]) # Output: Hello, world!
# Reversing the string
print(s[::-1]) # Output: !dlrow ,olleH
# Slice with step 2
print(s[::2]) # Output: Hlo ol!
# List
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Slice from the 2nd to the 5th element (excluding)
print(my_list[1:5]) # Output: [2, 3, 4, 5]
# Slice from the last element to the 3rd (excluding), with step -1
print(my_list[-1:2:-1]) # Output: [10, 9, 8, 7, 6, 5, 4]
# Tuple
my_tuple = (10, 20, 30, 40, 50)
# Slice from the 2nd to the 4th element (excluding)
print(my_tuple[1:4]) # Output: (20, 30, 40)
Using slices allows creating new objects with parts of data from the original sequence, making them an efficient tool for data manipulation.