Working with Python - Slicing the List
Introduction
In this blog post we are trying to discuss about Python List concept and how to Slicing the List.
Hope it will be interesting.
Characteristic of List
Here are some common characteristic of List
·
Values are ordered
·
Mutable
·
A list can hold any number of values
·
Value can have any data type
·
A list can add, remove, and alter the
values
How to
Create List
# Creating a Empty List
list=[]
#Creating List with ValueError
list=['Joydeep','Mayuree','Surrya']
print(list)
à['Joydeep', 'Mayuree', 'Surrya']
Assign a List Value to Variable
list=['Joydeep','Mayuree','Surrya']
name1=list[0]
name2=list[1]
print(name1)
print(name2)
àJoydeep
àMayuree
Slicing
the List
Before moving the Slicing Section we have to understand the
Indexing of List.
We have a list of Character
list=['J','O','Y','D','E','E','P']
We have two type of Indexing with List.
First one is Forward Indexing and second one is Backward Indexing.
The forward indexing starts from 0 and backward indexing starts
from -1
Stepping Forward
Take a simple example:
From the above List, we are going to print from position 0 to 3
forward.
list=['J','O','Y','D','E','E','P']
print(list[0:3])
à['J', 'O', 'Y']
You
are going to think why it is not going to print ‘J’,’O’,’Y’,’D’.
The
formula is From [Start Position] to [Last Position – 1]
Now
try this
list=['J','O','Y','D','E','E','P']
print(list[:3])
à['J', 'O', 'Y']
Here
in this example, we are not providing any Start Point, so it by default 0
Now
we have to understand the Jumping within the List
list=['J','O','Y','D','E','E','P']
print(list[:7:2])
à['J', 'Y', 'E', 'P']
The
formula is LIST[Start Position], [Last Position] – 1, [Step])
Stepping
Backward
The
formula is From [Start Position] to [Last Position + 1]
list=['J','O','Y','D','E','E','P']
print(list[-1:-3:-1])
à ['P', 'E']
Let’s
understand this example.
The
First position is -1. So it prints ‘P’
The
Last position is -3. But according to formula (-3 + 1) = -2. So it’s going to
print ‘E’
One
thing we have to remember, if the Step is Positive or Not Define, it’s a forward
movement List and the Step is Negative, it’s a backward movement List.
Hope you like it.
Great to understand
ReplyDeleteThanks
Delete