Python list slice | Get specific sets of sub-elements Array

As you know Python List is a collection that is ordered and changeable. if you don’t know then you must read the first Python List tutorial. Python List Slicing is a way to get a range of items in a list.

Note: List are index from 0 to size-1, with a step of 1.

Syntax

A syntax is where to start the slicing, where to end and specify the step.

Python list slice Examples

Let’s do multiple example of it.

1. Basic Example

Let’s do the basic example of list slicing.

Output: [‘c’]

2. Slice with Negative Indices

Example of passing negative indices while slicing a list.

Output: [‘a’, ‘b’]

3. Slice with Positive & Negative Indices

Using positive and negative indices at the same time in slice function.

Output: [‘b’]

4. Specify Step of the Slicing

The step parameter is optional and by default 1 and its used for specify the step.

Output: [3, 5, 7, 9]

5. Slice List at Beginning & End in Python

Omitting the start index starts the slice from the index 0. Meaning, L[:stop] is equivalent to L[0:stop]

Output: [1, 2, 3]

Q: How to Python slice list by value?

Answer: Use bisect module as part of the standard library. See the below example for slice the list by value in python.

Output:

Python list slice

Do comment if you have any suggestions and doubts on this tutorial.

Note:
IDE: PyCharm 2020.1.1 (Community Edition)
macOS 10.15.4
Python 3.7
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.