×

How to slice a list in python

When working with lists, we face situations where we may need a part of the list from one index to the other. Slicing is one of the simpler ways to do this. In this article, we will see different scenarios of slicing with examples.

Slicing

Slicing is the most common and easy way to split lists based on indices.

Syntax:

list_name [initialin: endin + 1: stepin]

Here,

  • initialin: The index from which the list has to be sliced. (Optional)
  • endin: The index till which the list has to be sliced. (Optional)
  • stepin: The gap to step from one index to the other index between the                first_index and the end_index. (Optional) (Default: 1)

Points to be noted:

  1. If the initial index is not mentioned, the list will be sliced from the start.
  2. If the final index is not mentioned, the list will be sliced till the end.
  3. Negative indexing is allowed to be used in slicing.
  4. When sliced, the list is not altered, rather, a copy of the sliced list is made, and we can assign it to a new list and work on it.
  5. We can work with the list from backward using a negative step index.
  6. When specifying the end index, we need to give the end index + 1 because the list will be sliced only till the specified index – 1.
  7. The index we give at the first index is also considered while slicing, unlike the end index.

Example:

list1 = [1, 2, 3, 4]
print ("The list from index 1 to 2: ",list1 [1 : 3])

Output:

The list from index 1 to 2: [2, 3]

Explanation:

The end index is given as 3. It is sliced till 3 – 1 = 2nd index. The list is sliced from 1st index to 2nd index: [2, 3]

How To Slice A List In PythonHere are different cases:

list1 = [1, 2, 3, 4]
print ("The list from index 0 to 2: ", list1[0 : 3])
print ("The list from index 0 to 3 with step=2: ", list1[0 : 4 : 2])
print ("The list from the start to 2nd index: ", list1 [ : 3])
print ("The list from the 1st index to the end: ", list1 [ 1 : ])
print ("The list with alternate indices: ", list1 [ : : 2])
print ("The exact same list: ", list1 [ : : ])

Output:

The list from index 0 to 2:  [1, 2, 3]
The list from index 0 to 3 with step=2:  [1, 3]
The list from the start to 2nd index:  [1, 2, 3]
The list from the 1st index to the end:  [2, 3, 4]
The list with alternate indices:  [1, 3]
The exact same list:  [1, 2, 3, 4]

Understanding:

The original list:

How To Slice A List In Python

  • [0 : 3] : From 0th index to (3 – 1) = 2nd index :

How To Slice A List In Python

  • [0 : 4 : 2]: From 0th index to 3rd index with step value = 2:

How To Slice A List In Python

  • [ : 3]: From the first (0th ) index to 2nd index:

How To Slice A List In Python

  • [1 : ]: From 1st index to the end of the list (3 + 1 = 4th ):

How To Slice A List In Python

  • [ : : 2]: From the first index to the last index with step value = 2:

How To Slice A List In Python

Negative indices:

Consider a list:

List1 = [1, 2, 3, 4]. The negative indices will look like this:

How To Slice A List In Python

The negative indexing starts from the end as -1, -2, -3, -4…

Slicing using Negative indices

Though the negative indices start from right to left, we need to give indices that go from left to right for slicing using negative indices.

How To Slice A List In Python

To get from -2 to -3rd indices, we need to give:

[-3 : -2] is correct

[-2 : -3] wrong

  • Like above, the last index has to be incremented to be considered.

Program:

list1 = [1, 2, 3, 4]
print ("The list from index -3 to -2: ", list1[-3 : -1])

Output:

The list from index -3 to -2:  [2, 3]

Explanation:

The last index we need: -2: -2 + 1: -1

[-3 : -1] : From -3rd index to -2nd index:

How To Slice A List In Python

More cases:

list1 = [1, 2, 3, 4]
print ("The list from index -3 to -2: ", list1 [-3 : -1])
print ("The list from index -3 to the end: ", list1 [-3 : ])
print ("The list from the start to -2 index: ", list1 [ : -1])
print ("The list with alternate elements: ", list1 [-4 : : 2])

Output:

The list from index -3 to -2:  [2, 3]
The list from index -3 to the end:  [2, 3, 4]
The list from the start to -2 index:  [1, 2, 3]
The list with alternate elements:  [1, 3]

Understanding:

  • [-3 : -1] -> from -3rd index to -1-1 = -2nd index:

How To Slice A List In Python

  • [-3 : ] -> from -3rd index till the end:

How To Slice A List In Python

  • [ : -1] -> from the start to -1 -> -1-1 = -2nd index:

How To Slice A List In Python

  • [-4 : : 2] = step = 2:

How To Slice A List In Python

Note: If we want the list to the end, we cannot give -1+1 = 0 index because the 0th index means the first element in the positive indices. So, we should leave it without giving any index.

Slicing with Negative step:

We can even give the step-index as negative. This parses the list in the reverse order from right to left.

Program:

list1 = [1, 2, 3, 4]
print ("The reverse string: ",list1 [ : : -1])
print ("Negative step 2", list1 [ : : -2])
print ("Negative step 3",list1 [ : : -3])
print ("Negative step 4",list1 [ : : -4])

Output:

The reverse string:  [4, 3, 2, 1]
Negative step 2 [4, 2]
Negative step 3 [4, 1]
Negative step 4 [4]

Understanding:

It is the same as the above conditions. The only change is the parsing is done from right to left:

How To Slice A List In Python

Step = -1:

How To Slice A List In Python

Step = -2:

How To Slice A List In Python

This is the concept of slicing.

Here are some more examples:

Slicing when we don’t know the length of the list:

In this case, we can use a function in Python called the len() to find the length of the list.

Program:

list1 = [23, 78, 45, 68, 34, 21]
length = len (list1)
print ("The length of the list is ", length)
halve = length // 2
print ("Slicing the list into halve: ", list1 [ : halve])
print ("Slicing for the second halve: ",list1 [halve : ])

Output:

The length of the list is  6
Slicing the list into half:  [23, 78, 45]
Slicing for the second half:  [68, 34, 21]

Understanding:

Here, we made our list. But, in some scenarios, we won't know the details of the list. In such cases, we can use the len () function to access the length of the list. The last index of the list will be length – 1. Now, we can easily go for slicing.

slice () function in Python:

Example program:

a = [1, 2, 3, 4, 5, 6]
x = slice (3, 5)
print (a [x])

Output:

[4, 5]

Explanation: The slice function does the same as we saw in above section. To use the function, we need to give the indices we need in the slice function and assign them to a variable. Then, we need to give that as an index to the list to get the sliced list.

Example:

list1 = [23, 78, 45, 68, 34, 21]
length = len (list1)
print ("The length of the list is ", length)
halve = length // 2
a = slice (0 , halve)
print ("Slicing the list into halve: ", list1 [a])

Output:

The length of the list is 6
Slicing the list into half:  [23, 78, 45]

Related Topics

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Function annotations() in Python

What is Function Annotations? Function annotations provide a way related to different parts of a function at compile time with arbitrary Python expressions. It doesn’t have life in Python runtime execution....

3 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Python min() function

Python min() function returns you the minimum value element in an iterable. We can also use this function to determine the smallest value among various arguments passed to this function. We...

4 minutes read.

Mrcnn Python

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

Best Database in Python

In this tutorial, Firstly, we will understand what the term database means. Further, we will see the various databases supported in Python and when to use which one. Further, we...

7 minutes read.

How to Install Python

Python Installation Guide Step by Step Installing Python is quite simple and easy. In this tutorial, we will show stepwise procedure to install Python and set up the Python environment in different...

2 minutes read.

Get Bounding Box Co-ordinates Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

6 minutes read.

Python program to find the greatest among two numbers

Python program to find the greatest among two numbers We have many approaches to get the largest number among the two numbers, and here we will discuss a few of them....

2 minutes read.

Python String rindex() method

Python String rindex() method The string. rindex() method in Python returns the highest index of the substring inside the string (if found). If the substring is not found, it raises an...

2 minutes read.

Python String

Python String Python string is considered as the most popular data type present in Python language. In Python, string data type is the collection of characters, letters, white spaces etc. written...

31 minutes read.

How to create a class in python

In any programming language, a class is a user-defined plan or blueprint using which objects or instances of the class are created. You may wonder why we need classes in programming....

5 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python program to check if two strings are anagram or not

Python program to check if two strings are anagram or not Problem: This is a python program that takes two strings and checks if given strings are anagram or not. Examples: Input: string1...

1 minute read.

Checking whether a String Contains a Set of Characters in python

In this tutorial, we will learn how to examine or check whether a string contains any set of characters or a substring and if it contains, we will learn how...

6 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

How to make API calls in Python

Information is extremely critical these days since it drives applications and organizations. It is subsequently critical to figure out how to get this information to serve your application. In fundamental...

4 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python locals() function

Python locals() function The locals() function in Python updates and returns a dictionary representing the current local symbol table. Syntax locals() Parameter NA Return This function returns the local symbol table as a dictionary or returns free...

1 minute read.