Categories
python

Slicing in python

In this post, let us discuss slicing in python with examples.

How Indexing works ?

For your reminder, Indexing starts from zero.
In the below example, a[0] & a[1] help us to get the element present in the zeroth and first index position

Program

print("creating a new list")
a=[9,8,7,6,5,4,3,2,1]
print("printing the elements of the list")
print(a)
print("printing the first element")
print(a[0])
print("printing the second element")
print(a[1])

Output

creating a new list
printing the elements of the list
[9, 8, 7, 6, 5, 4, 3, 2, 1]
printing the first element
9
printing the second element
8

What is Slicing ?

Slicing in python helps us in getting the specific range of elements based on their position from the collection.

Here comes the syntax of slicing which lists the range from index position one to two. It neglects the element present in the third index.
Below is the official document
https://docs.python.org/2.3/whatsnew/section-slices.html

Slicing in Python

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing the first 3 elements of a list")
print(a[0:3])
print("other way to print first 3 elements of a list")
print(a[:3])

Output

printing the first 3 elements of a list
[9, 8, 7]
other way to print first 3 elements of a list
[9, 8, 7]

Positive and Negative indexing in slicing

There are two types of indexing available :

1) Positive Indexing
2) Negative Indexing

Positive Indexing

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing second and third element in a list")
print(a[1:3])

Output

printing second and third element in a list
[8, 7]

Negative indexing

Program

a=[9,8,7,6,5,4,3,2,1]
print("printing the last element")
print(a[-1])
print("printing last three elements in a list")
print(a[-3:])
print("printing from second element till second last element")
print(a[1:-1])

Output

printing the last element
1
printing last three elements in a list
[3, 2, 1]
printing from second element till second last element
[8, 7, 6, 5, 4, 3]

Interview Q&A

How to reverse the elements present in a list?

Program

a=[9,8,7,6,5,4,3,2,1]
print("Reversing the elements")
print(a[::-1])

Output

Reversing the elements
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Create dataframe in python

Leave a Reply

Your email address will not be published. Required fields are marked *