Python Program to Slice Lists – 2024

Hey guys, in this blog we will see a Python Program to Slice Lists.

The format for list slicing is [start:stop:step].

  • start is the index of the list where slicing starts.
  • stop is the index of the list where the slicing ends.
  • step allows you to select the nth item within the range start to stop.

Get all the Items

# Python Program to Slice Lists

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

print(my_list[:])

Output

[1, 2, 3, 4, 5]

When we want to access all the items of the list we use [:] which means all.

Get all the Items After a Specific Position

# Python Program to Slice Lists

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

print(my_list[2:])

Output

[3, 4, 5]
  • When we want to access all the items of the list after a specific position we use [2:] which means all the elements starting from position 2 to end.
  • Indexing will be 0 indexed which means position 2 in 0 indexed will actually be position 3 if we start counting from 1.
  • Notice position 2 is inclusive.

Get all the Items Before a Specific Position

# Python Program to Slice Lists

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

print(my_list[:2])

Output

[1, 2]
  • When we want to access all the items on the list before a specific position we use [:2] which means all the elements start from starting to this position.
  • Notice position 2 is exclusive.

Get all the Items from One Position to Another Position

# Python Program to Slice Lists

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

print(my_list[2:4])

Output

[3, 4]
  • When we want to access all the list items in a specific range we use [2:4] which means all the elements starting from position 2 to 4.
  • Notice that 2 is inclusive and 4 is exclusive.

Get the Items at Specified Intervals

# Python Program to Slice Lists

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

print(my_list[::2])

Output

[1, 3, 5]
  • When we want to change the step size while accessing items of a list we use [::2] which means all the elements from start to end but the step size is 2.
  • After 1 it should ideally print 2 but as our step size is 2 it will print 3.

Start indexing from the last item

If you want the indexing to start from the last item, you can use the negative sign -.

# Python Program to Slice Lists

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

print(my_list[::-2])

Output

[5, 3, 1]
  • Similar to above but here step size is -2 which means starting from the end and taking 2 steps back every time.

Slicing items from one position to another

If you want the items from one position to another, you can mention them from start to stop.

# Python Program to Slice Lists

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

print(my_list[1:4:2])

Output

[2, 4]

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *