fbpx

In this article we will see a quick guide on how to create Python Lists . We will then learn to apply indexing and slicing on list created just like you do for python String. We will also try to modify the list . Let’s start a quick and easy guide of Python List Creation, Indexing and Slicing. Lists are created using bracket [] and elements are separated by comma. It’s mutable, means the elements inside a list can be changed. List is a build in sequence data type which can stores different object types like integers and String. Let’s create a lists!

1. Python List Creation

To create a list, enclose all elements in square brackets ([]) separated by commas.

mylist=[23,”cks”,34.5 , “T” , “city”]

2. Accessing List elements using indexing

you can use indexing to access elements in a Python list just like you would with a Python string . Python uses zero-based indexing, meaning the first element is at index 0 , second at index 1 and so on .Negative index count from the end of the list.

mylist[1]

3. Apply Slicing on Python List:

Slicing allows you to extract a portion of a list. It uses the format list[start : stop : step ]:

— start: The starting index (inclusive).
— stop: The stopping index (exclusive).
— step: The step size (optional).
Note: Negative step size consider step from the end of the list.

mylist[1: : ]

Below code will Grab all element from list up to index 3

mylist[ :4: ]

Below code reverse the element in the list by providing -1 at step in [start : stop : step]

mylist[ : :-1]

4. Modify the Python List:

Python list is mutable that is we can modify it . You can change list elements using indexing. Below code will modify the list element stored at index 1 with ‘Singh’ Value .

mylist[1]= ‘Singh’

More Resources:

Python List Colab

DigitalOcean Referral Badge

By tecksed

Leave a Reply

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

×