Python Program to Slice Lists

 

Get all the Items

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

print(my_list[:])

Output

[1, 2, 3, 4, 5]

Get all the Items After a Specific Position

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

print(my_list[2:])

Output

[3, 4, 5]

Get all the Items Before a Specific Position

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

print(my_list[:2])

Output

[1, 2]

Get all the Items from One Position to Another Position

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

print(my_list[2:4])

Output

[3, 4]

Get the Items at Specified Intervals

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

print(my_list[::2])

Output

[1, 3, 5]

0 Comments