Thursday, February 29, 2024

Slice Object in Python

Built-in type that represents a range of indices. It's commonly used with sequences (like lists, strings, and tuples) to extract portions of the sequence.


list_of_students = [(1,"Joe"), (2,"John"), (3,"Jacob"), (4,"Jack"),
 (5,"Karan"), (6, "Kavya"), (7,"Kamal")]

odd_slice = slice(0,len(list_of_students),2)
even_slice = slice(1,len(list_of_students),2)
list_of_group_one = list_of_students[odd_slice]
list_of_group_two = list_of_students[even_slice]
print(list_of_group_one)
print(list_of_group_two)

Output:

[(1, 'Joe'), (3, 'Jacob'), (5, 'Karan'), (7, 'Kamal')]
[(2, 'John'), (4, 'Jack'), (6, 'Kavya')]

No comments:

Post a Comment