NbShare
  • Nbshare Notebooks

  • Table of Contents

  • Python Utilities

    • How To Install Jupyter Notebook
    • How to Upgrade Python Pip
    • How To Use Python Pip
  • Python

    • Python Datetime
    • Python Dictionary
    • Python Generators
    • Python Iterators and Generators
    • Python Lambda
    • Python Sort List
    • String And Literal In Python 3
    • Strftime and Strptime In Python
    • Python Tkinter
    • Python Underscore
    • Python Yield
  • Pandas

    • Aggregating and Grouping
    • DataFrame to CSV
    • DF to Numpy Array
    • Drop Columns of DF
    • Handle Json Data
    • Iterate Over Rows of DataFrame
    • Merge and Join DataFrame
    • Pivot Tables
    • Python List to DataFrame
    • Rename Columns of DataFrame
    • Select Rows and Columns Using iloc, loc and ix
    • Sort DataFrame
  • PySpark

    • Data Analysis With Pyspark
    • Read CSV
    • RDD Basics
  • Data Science

    • Confusion Matrix
    • Decision Tree Regression
    • Logistic Regression
    • Regularization Techniques
    • SVM Sklearn
    • Time Series Analysis Using ARIMA
  • Machine Learning

    • How To Code RNN and LSTM Neural Networks in Python
    • PyTorch Beginner Tutorial Tensors
    • Rectified Linear Unit For Artificial Neural Networks Part 1 Regression
    • Stock Sentiment Analysis Using Autoencoders
  • Natural Language
    Processing

    • Opinion Mining Aspect Level Sentiment Analysis
    • Sentiment Analysis using Autoencoders
    • Understanding Autoencoders With Examples
    • Word Embeddings Transformers In SVM Classifier
  • R

    • DataFrame to CSV
    • How to Create DataFrame in R
    • How To Use Grep In R
    • How To Use R Dplyr Package
    • Introduction To R DataFrames
    • Tidy Data In R
  • A.I. News
NbShare Notebooks
  • Publish Your Post On nbshare.io

  • R Python Pandas Data Science Excel NLP Numpy Pyspark Finance

Understand Python Slicing

Python slicing is used to slice lists or tuples. Let us learn Python slicing through examples.

Let us declare a Python list.

In [1]:
x = [1,2,3,4,5,6,7,8,9]

Python slicing can be done in two ways...
x[start:stop:step] -- Select items at every step (index) from Start through stop-1
x[slice(start,stop,step) -- Select items at every step (index) from Start through stop-1
Note step (argument) is optional

In [2]:
x[0:1]
Out[2]:
[1]
In [3]:
x[0:1:1]
Out[3]:
[1]
In [4]:
x[slice(0,1)]
Out[4]:
[1]
In [5]:
x[slice(0,1,1)]
Out[5]:
[1]

Note step parameter is optional, by default it is 1.

Python slice all but first element

In [6]:
x[1:]
Out[6]:
[2, 3, 4, 5, 6, 7, 8, 9]

Python slice all but last element

In [7]:
x[:8]
Out[7]:
[1, 2, 3, 4, 5, 6, 7, 8]

Python slice and copy the whole list

In [8]:
x[:]
Out[8]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Python slice every other element in the list

The below command means start from index 0 and extract every 2nd element.
index 0 , index (2) 0 +2, index (4) 0 + 2 +2, index (6) 0 + 2 + 2 +2 , index (8) 0 + 2 + 2 + 2 +2

Note two colons in the below syntax. There is nothing between Ist and 2nd colon that means evreything from start to end of list.

In [9]:
x[0::2]
Out[9]:
[1, 3, 5, 7, 9]

Python Slicing - Negative and Positive step values

Negative step of -1 means go from right to left
Positive step of 1 means go from left to right

Python slicing using negative indices

Negative number -1 means last element, -2 means seconda last element so on and so forth.

In [10]:
x[-1]
Out[10]:
9

The below syntax will print nothing, because index is starting from -1 which means last element in the list then it goes to index 0 because by default step is 1 but our "stop" is -3. To fix this we will have to give step of -1.

In [11]:
x[-1:-3]
Out[11]:
[]

As we can see, the index will start from -1, the last element, then goes to -2 because step is -1, then stops at -3

In [12]:
x[-1:-3:-1]
Out[12]:
[9, 8]

Python Reverse all the items in the array using Slicing

In [13]:
x[::-1]
Out[13]:
[9, 8, 7, 6, 5, 4, 3, 2, 1]

Note in the above, since step is -1, Python considers start:stop as -1:-10, we can re-write above as shown below.

In [14]:
x[-1:-10:-1]
Out[14]:
[9, 8, 7, 6, 5, 4, 3, 2, 1]

print last 3 elements. Note below syntax means -3 to last element (right to left) and step is 1 by default

In [15]:
x[-3:]
Out[15]:
[7, 8, 9]

Below syntax means, start at -3 index, then go to (-5) -3-2 so on and so forth to all the way to start of the list (right to left) because step is -1.

In [16]:
x[-3::-2]
Out[16]:
[7, 5, 3, 1]

Python Slicing - Reverse first two items

In [17]:
x[1::-1]
Out[17]:
[2, 1]

Let us see how did the above slicing syntax works.
The index will start at...
index 1, index (0) 1-1
Note -1 tells it go from right to left

In [18]:
x[1::-1]
Out[18]:
[2, 1]

Python Everything Except the last two items - Reversed

In [19]:
x[-3::-1]
Out[19]:
[7, 6, 5, 4, 3, 2, 1]

Note all the above can be used with slice method. The different is instead of ":" (colon) use None to indicate end or start of list index.

In [20]:
x[slice(-3,None,-1)]
Out[20]:
[7, 6, 5, 4, 3, 2, 1]

Related Notebooks

  • Json Python
  • Python Lambda
  • Python Generators
  • Python Yield
  • Understand Tensors With Numpy
  • Append In Python
  • Python If Not
  • Dictionaries In Python
  • Python Datetime Module

Register

User Already registered.


Login

Login

We didn't find you! Please Register

Wrong Password!


Register
    Top Notebooks:
  • Data Analysis With Pyspark Dataframe
  • Strftime and Strptime In Python
  • Python If Not
  • Python Is Integer
  • Dictionaries in Python
  • How To install Python3.9 With Conda
  • String And Literal In Python 3
  • Privacy Policy
©