Open In App

Python List Slicing

Last Updated : 20 Jun, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, list slicing is a common practice and it is the most used technique for programmers to solve efficient problems. Consider a Python list, in order to access a range of elements in a list, you need to slice a list. One way to do this is to use the simple slicing operator i.e. colon(:). With this operator, one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list from the existing list.

Python List Slicing Syntax

The format for list slicing is of Python List Slicing is as follows:

Lst[ Initial : End : IndexJump ]

If Lst is a list, then the above expression returns the portion of the list from index Initial to index End, at a step size IndexJump.

Indexing in Python List

Indexing is a technique for accessing the elements of a Python List. There are various ways by which we can access an element of a list.

Positive Indexes

In the case of Positive Indexing, the first element of the list has the index number 0, and the last element of the list has the index number N-1, where N is the total number of elements in the list (size of the list).

Positive Indexing of a Python List

Positive Indexing of a Python List

Example:

In this example, we will display a whole list using positive index slicing.

Python
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[::])

Output:

[50, 70, 30, 20, 90, 10, 50]

Negative Indexes

The below diagram illustrates a list along with its negative indexes. Index -1 represents the last element and -N represents the first element of the list, where N is the length of the list.

Negative Indexing of a Python List

Negative Indexing of a Python List

Example:

In this example, we will access the elements of a list using negative indexing.

Python
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[-7::1])

Output:

[50, 70, 30, 20, 90, 10, 50]

Slicing

As mentioned earlier list slicing in Python is a common practice and can be used both with positive indexes as well as negative indexes. The below diagram illustrates the technique of list slicing:

Python List Slicing

Python List Slicing

Example:

In this example, we will transform the above illustration into Python code.

Python
# Initialize list
Lst = [50, 70, 30, 20, 90, 10, 50]

# Display list
print(Lst[1:5])

Output:

[70, 30, 20, 90]

Examples of List Slicing in Python

Let us see some examples which depict the use of list slicing in Python.

Example 1: Leaving any argument like Initial, End, or IndexJump blank will lead to the use of default values i.e. 0 as Initial, length of the list as End, and 1 as IndexJump.

Python
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Show original list
print("Original List:\n", List)

print("\nSliced Lists: ")

# Display sliced list
print(List[3:9:2])

# Display sliced list
print(List[::2])

# Display sliced list
print(List[::])

Output:

Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Sliced Lists:
[4, 6, 8]
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Example 2: A reversed list can be generated by using a negative integer as the IndexJump argument. Leaving the Initial and End as blank. We need to choose the Initial and End values according to a reversed list if the IndexJump value is negative. 

Python
# Initialize list
List = ['Geeks', 4, 'geeks !']

# Show original list
print("Original List:\n", List)

print("\nSliced Lists: ")

# Display sliced list
print(List[::-1])

# Display sliced list
print(List[::-3])

# Display sliced list
print(List[:1:-2])

Output:

Original List:
['Geeks', 4, 'geeks !']

Sliced Lists:
['geeks !', 4, 'Geeks']
['geeks !']
['geeks !']

Example 3: If some slicing expressions are made that do not make sense or are incomputable then empty lists are generated.

Python
# Initialize list
List = [-999, 'G4G', 1706256, '^_^', 3.1496]

# Show original list
print("Original List:\n", List)

print("\nSliced Lists: ")

# Display sliced list
print(List[10::2])

# Display sliced list
print(List[1:1:1])

# Display sliced list
print(List[-1:-1:-1])

# Display sliced list
print(List[:0:])

Output:

Original List:
[-999, 'G4G', 1706256, '^_^', 3.1496]

Sliced Lists:
[]
[]
[]
[]

Example 4: List slicing can be used to modify lists or even delete elements from a list.

Python
# Initialize list
List = [-999, 'G4G', 1706256, 3.1496, '^_^']

# Show original list
print("Original List:\n", List)


print("\nSliced Lists: ")

# Modified List
List[2:4] = ['Geeks', 'for', 'Geeks', '!']

# Display sliced list
print(List)

# Modified List
List[:6] = []

# Display sliced list
print(List)

Output:

Original List:
[-999, 'G4G', 1706256, 3.1496, '^_^']

Sliced Lists:
[-999, 'G4G', 'Geeks', 'for', 'Geeks', '!', '^_^']
['^_^']

Example 5: By concatenating sliced lists, a new list can be created or even a pre-existing list can be modified. 

Python
# Initialize list
List = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# Show original list
print("Original List:\n", List)

print("\nSliced Lists: ")

# Creating new List
newList = List[:3]+List[7:]

# Display sliced list
print(newList)

# Changing existing List
List = List[::2]+List[1::2]

# Display sliced list
print(List)

Output:

Original List:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Sliced Lists:
[1, 2, 3, 8, 9]
[1, 3, 5, 7, 9, 2, 4, 6, 8]

Python List Slicing – FAQs

What does distinct() do in Python?

Python itself does not have a built-in distinct() function. However, the concept of “distinct” is commonly used in SQL databases to retrieve unique values. In Python, you can achieve the same effect using a set to filter out duplicate elements from an iterable.

How do you check if a list contains unique values in Python?

To check if a list contains only unique values, you can compare the length of the list with the length of the set created from the list:

def is_unique(lst):
return len(lst) == len(set(lst))
# Example usage
my_list = [1, 2, 3, 4, 5]
print(is_unique(my_list)) # Output: True
my_list_with_duplicates = [1, 2, 3, 3, 4, 5]
print(is_unique(my_list_with_duplicates)) # Output: False

What built-in Python data structure can be used to get unique values from a list?

The set data structure is used to get unique values from a list. A set automatically removes duplicates and maintains only unique elements.

my_list = [1, 2, 2, 3, 4, 4, 5]
unique_values = list(set(my_list))
print(unique_values) # Output: [1, 2, 3, 4, 5]

How do I count unique items in a list in Python?

To count the number of unique items in a list, convert the list to a set and get the length of the set:

my_list = [1, 2, 2, 3, 4, 4, 5]
unique_count = len(set(my_list))
print(unique_count) # Output: 5

How do I check if a list contains duplicates in Python?

To check if a list contains duplicates, you can compare the length of the list with the length of the set created from the list. If they are not equal, the list contains duplicates:

def contains_duplicates(lst):
return len(lst) != len(set(lst))
# Example usage
my_list = [1, 2, 3, 3, 4, 5]
print(contains_duplicates(my_list)) # Output: True
my_unique_list = [1, 2, 3, 4, 5]
print(contains_duplicates(my_unique_list)) # Output: False


Previous Article
Next Article

Similar Reads

Python | Slicing list from Kth element to last element
Python list slicing slices the list from start index till end - 1, specified as list elements. So its tricky when we require to also slice the last element of list. Trying to slice till list size + 1 gives an error. Let's discuss ways in which last element can be included during a list slice. Method #1 : Using None During list slicing, giving the d
6 min read
Python | Variable list slicing
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths according to the input given in other list. This problem has its potential application in web development. Let's discuss certain ways in which this can be done. Method #1 : Using itertools.islice() + list comprehension The list com
7 min read
Python | Alternate range slicing in list
List slicing is quite common utility in Python, one can easily slice certain elements from a list, but sometimes, we need to perform that task in non-contiguous manner and slice alternate ranges. Let's discuss how this particular problem can be solved. Method #1 : Using list comprehension List comprehension can be used to perform this particular ta
6 min read
Python | Get the substring from given string using list slicing
Given a string, write a Python program to get the substring from given string using list slicing. Let’s try to get this using different examples. What is substring? A substring is a portion of a string. Python offers a variety of techniques for producing substrings, as well as for determining the index of a substring and more. Syntax of list slicin
4 min read
Python | Custom slicing in List
Sometimes, while working with Python, we can come to a problem in which we need to perform the list slicing. There can be many variants of list slicing. One can have custom slice interval and slicing elements. Let's discuss problem to such problem. Method : Using compress() + cycle() The combination of above functions can be used to perform this pa
2 min read
Python | Custom List slicing Sum
The problem of slicing a list has been dealt earlier, but sometimes we need to perform the slicing in variable lengths and its summation according to the input given in other list. This problem has its potential application in web development. Let’s discuss certain ways in which this can be done. Method #1 : Using itertools.islice() + sum() + list
7 min read
Python - Convert 2D list to 3D at K slicing
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] , K
4 min read
Program to cyclically rotate an array by one in Python | List Slicing
Given an array, cyclically rotate the array clockwise by one. In this article, we will see how to cyclically rotate an array by one in Python. Example Input: arr = [1, 2, 3, 4, 5]Output: arr = [5, 1, 2, 3, 4]Reference: Program to cyclically rotate an array by one Python Program to Cyclically Rotate an Array by One in PythonBelow are the methods or
2 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Slicing List of Tuples in Python
Slicing, a powerful feature in Python, allows us to extract specific portions of data from sequences like lists. When it comes to lists of tuples, slicing becomes a handy tool for extracting and manipulating data. In this article, we'll explore five simple and versatile methods to slice lists of tuples in Python, accompanied by code examples. Slici
2 min read
Article Tags :
Practice Tags :