×

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 md5_file() function

Python md5_file() function The md5_file() function in PHP calculates the md5 hash of a given file. Syntax md5_file ( string $filename [, bool $raw_output ] )  Parameter filename(required)- This parameter signifies the file to be calculated. raw_output(optional)- It takes a boolean value that specifies hex or binary...

1 minute read.

Python try except

Before diving right into loads of syntax we need to know what does try except is used for and how it helps users in writing programs What is Python try except? Python...

5 minutes read.

Python Dictionary keys() method

Python Dictionary keys() method The dictionary.keys() method in Python returns a view object that displays a list of all the keys in the dictionary Syntax dictionary.keys() Parameter NA Return This method returns a view object that displays...

2 minutes read.

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

Python Program to Find the gcd of Two Numbers

Introduction Greatest Common Divisor is the full form of gcd. The greatest common divisor, or GCD, of two numbers, is a value that can exactly divide the two digits and is...

5 minutes read.

How to Sort a String in Python?

The characters in the string are sorted or put in alphabetical order using the sort string function in Python. Python has built-in techniques for sorting strings available. Since we occasionally...

6 minutes read.

Is Python Case Sensitive

Case sensitivity is the mode of dealing with the written alphabet. The cases of the alphabet are examined and based on these words are being treated. The uppercase and lowercase...

3 minutes read.

Python Scikit-image | Image Processing Using Scikit-Image

What is Image Processing? The world is defined with images and, every image has its different specialties. An image can contain much-needed information that can be helpful in various ways. The process...

4 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

How to Update Python?

How to Update Python In this article, we will discuss how we can update Python in our system. For a better understanding, this article will cover all the steps right from installation...

4 minutes read.

Python Queue

Python Queue There are various day to day activities where we find ourselves engaged with queues. Whether it is waiting in toll tax lane or standing on the billing counter for...

7 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Standard GUI Unit Converter using PyQt5 in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Reverse a String in Python

Python is an object-oriented high-level programming language. Python has dynamic semantics and has high-level built-in data structures which support dynamic typing and dynamic binding. Python provides rapid development. It has...

4 minutes read.

Create First GUI Application using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

6 minutes read.

Python Control Flow Statements

This article aims to introduce you to what control flow statements are in general and Control Flow Statements in Python programming Language, the Importance of control flow statements and look...

3 minutes read.