Python List - Slice first N elements


Python List - Slice first N elements

To slice the first N element from a given list in Python, you can use regular slicing expression with a specified end index N.

If N is the number of first elements that we need to slice in a list my_list, then the expression is

my_list[:N]

The above expression returns a new list with the first N elements from the original list.

Examples

In the following examples, we shall go through use cases of slicing first N elements from a given list, when the length of given list is greater than the specified N, and when then the length of given list is less than the specified N.

1. Slice first 3 elements from list in Python

In this example, we are given a list in my_list. We have to slice the first 3 elements from this list using list slicing.

Steps

  1. Given a list in my_list with six elements.
my_list = [10, 20, 30, 40, 50, 60]
  1. Given N to slice first N elements from the list.
N = 3  
  1. Use list slicing to slice the first N elements of the list my_list.
my_list[:N]

This returns a list with the first N elements. Assign it to a variable, say sliced_list.

sliced_list = my_list[:N]
  1. You may print the sliced list to output.
print(sliced_list)

Program

The complete program to slice first N elements from a Python list.

Python Program

# Given list
my_list = [10, 20, 30, 40, 50, 60]

# Number of elements to slice from the start
N = 3  

# Slice the list
sliced_list = my_list[:N]

# Print sliced list
print(sliced_list)

Output

[10, 20, 30]

2. Slice first 3 elements from list in Python, but length of list is less than 3

In this example, we are given a list in my_list with only two elements. We have to slice the first 3 elements from this list.

If the length of given list is less than the N (number of first elements to slice), a copy of the original list is returned by the slice expression my_list[:N].

Python Program

# Given list
my_list = [10, 20]

# Number of elements to slice from the start
N = 3  

# Slice the list
sliced_list = my_list[:N]

# Print sliced list
print(sliced_list)

Output

[10, 20]

Summary

In this Python lists tutorial, we have seen how to slice the first N elements of a given list using regular slicing expression, provided a step by step explanation, and examples.