Python slice Function |::-1 shorthand, (Array, List, Tuple, String)

Python slice function returns a slice object that can use used to slice strings, lists(Array), tuple, etc. Means slice object is used to specify how to slice a sequence like stringsliststuples.

Syntax

Parameters

  • start  – The slicing of the object starts. Optional and Default is NONE.
  • stop – The slicing stops at index stop -1 (last element) and its required.
  • step – Determines the increment between each index for slicing. Optional and Default is NONE.

Return value:

It returns a slice object.

Example of Python slice Funciton

Let’s do coding:-

Create a slice object

Output:

slice(None, 3, None)
slice(1, 5, 2)

1. String slicing

Example of python slice string. First create a slice object and then use to it slice string. Passing only stop value.

Output: Hello

Read more: Python slice string Examples

2. List slicing

Output: [1, 2, 3]

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

3. Tuple slicing

Same as String and list you can slice tuple:-

Output: (1, 2, 3)

Python slice shorthand | Understanding slice notation

Slice notation is used to extract a substring.

There is also the step value, which can be used with any of the above:

List Slicing Shorthand

Output:

[‘a’, ‘b’, ‘Python’]
[‘z’, ‘Tutorial’]
[‘a’, ‘b’, ‘Python’, ‘z’, ‘Tutorial’]

::-1 python Slice Notation

You can now easily extract the elements of a list that have even indexes:

This also works for List, arrays, and strings:

Output: (1, 3, 5)

Q: How to Python slice list by value

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

Output:

Python slice Function

Python list slice loop

This code snippet to be very interesting.

Output:

[0, 1, 2, 0]
[0, 1, 2, 1]
[0, 1, 2, 2]
[0, 1, 2, 2]

Do comment if you have any doubts and suggestion 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.