List in Python

Slicing of a List in Python

A list in Python is collection of values of any type such as integer, float, string or a complex number in a square bracket separated by comma.

For example
If you can create a list l as follows
l=[50, “Post”, “Network”, 50.3, 80, 100, 150, 180, 200, 300]
In the above list you can see all types of objects integer, string and float.
Moreover, you can access each element by list name with index by using two ways.
The first way is called forward indexing, in which elements are accessed from left to right using indices 0, 1, 2, 3, 4, 5, …….,n-1.
Where n is size of the list.
For example
50 can be accessed using l[0]
“Post” can be accessed using l[1]
“Network” can be accessed using l[2]
“50.3” can be accessed using l[3]
and so on.

Slicing of a List in Python

 

The second way is called backward indexing, in which elements are accessed from right to left using indices -1, -2, -3, -4, -5, …….,-n.
Where n is size of the list.
For example
300 can be accessed using l[-1]
200 can be accessed using l[-2]
“Network” can be accessed using l[-3]
“50.3” can be accessed using l[-4]
and so on.

List in Python

 

 

Slicing of a list in Python-

Slicing of a list in Python refers to take portion and create a new list.
The syntax for creating a new list using slicing is
nl=l[begin:end-1]

Where l is the old list and nl is new list and begin is starting index and end is the last index.

 

Slicing Using Forward Indexing-

l=[50, “Post”, “Network”, 50.3, 80, 100, 150, 180, 200, 300]
nl=l[2:5]
print(nl)
Then output would be a new list
[‘Network’, 50.3, 80]

Slicing  Using Backward Indexing-

Example of slicing using backward indexing
l=[50, “Post”, “Network”, 50.3, 80, 100, 150, 180, 200, 300]
nl=l[-8:-5]
print(nl)
Then output would be
[‘Network’, 50.3, 80]

 

 

 

Leave a Comment

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

©Postnetwork-All rights reserved.