Page Contents
Python list is used to store multiple items in a single variable . Python list is surrounded by square brackets ([]
) . Python provides total 4 built-in data types to store collection of data of which one is List . The other data types are Tuple , Set and Dictionary .
How to create a List in Python?
There are multiple ways to create a Python List –
- Using square bracket (
[]
) - Using
list()
function - Using list comprehension
To check if it is a list or not we can use type()
function .
# Creating a list in Python
# Using square bracket ([])
list_from_bracket = ["Rajkumar","apple",True,1,2.5,10]
print(list_from_bracket)
# checking the type
print("type of list_from_bracket",type(list_from_bracket))
# using list() function
list_from_function = list(("Rajkumar","apple",True,1,2.5,10))
print(list_from_function)
# checking the type
print("type of list_from_function",type(list_from_function))
# using list comprehension
list_from_comprehension = [item for item in range(5)]
print(list_from_comprehension)
# checking the type
print("type of list_from_comprehension",type(list_from_comprehension))
['Rajkumar', 'apple', True, 1, 2.5, 10] type of list_from_bracket <class 'list'> ['Rajkumar', 'apple', True, 1, 2.5, 10] type of list_from_function <class 'list'> [0, 1, 2, 3, 4] type of list_from_comprehension <class 'list'>
- In the above code we have created list using various ways
- First we have created list using square bracket (
[]
) . Then we have printed the list and also its type . - Second we have created list using
list()
. Then we have printed the list and also its type . - Third we have created list using list comprehension . Then we have printed the list and also its type .
- From the output we can see that in every case type is list .
Note :
List items are separated by comma (,
) and it can be of any type as we have seen in the previous code .
Characteristics of a List in Python
Python list is indexed , ordered and mutable(changeable) collection of items . It also allows duplicate values .
Python list is indexed | How to access elements of list in Python ?
We can access elements from a list using its index . So first we need to know about how indexing works in Python list . For this reason we need to see the below image –
From the above image we can see that in Python index starts from 0
. So , index of "Apple"
is 0
, index of True
is 1
and so on . We can also see that length of the given list is 5
but the last index number is 4
.
There is also one concept in Python that is negative indexing . Negative indexing in Python starts from -1
which points to the last element . We can see from the above image that -1
index points to the last element "Banana"
, -2
index points to the 2nd last character "Mango"
.
Example 1:
mylist = ["Apple",True,100,"Mango","Banana"]
# Accessing first element
print("mylist[0] =",mylist[0])
# Accessing second element
print("mylist[1] =",mylist[1])
# Accessing last element
print("mylist[len(mylist)-1] =",mylist[len(mylist)-1])
mylist[0] = Apple mylist[1] = True mylist[len(mylist)-1] = Banana
- In the above code first we have declared a list
mylist
as["Apple",True,100,"Mango","Banana"]
- Then we have printed first element of the list by
mylist[0]
that is"Apple"
- After that we have printed second element of the list by mylist[1] that is
True
- Then we have printed last element of the list by
mylist[len(mylist)-1]
that is"Banana"
. As length of the list is5
somylist[len(mylist)-1]
treated asmylist[4]
.
Example 2:
mylist = ["Apple",True,100,"Mango","Banana"]
# Accessing last element
print("mylist[-1] =",mylist[-1])
# Accessing second last element
print("mylist[-2] =",mylist[-2])
# Accessing first element
print("mylist[-len(mylist)] =",mylist[-len(mylist)])
mylist[-1] = Banana mylist[-2] = Mango mylist[-len(mylist)] = Apple
- In the above code first we have declared a list
mylist
as["Apple",True,100,"Mango","Banana"]
- Then we have printed last element of the list by
mylist[-1]
that is"Banana"
- After that we have printed second last element of the list by
mylist[-2]
that is"Mango"
- Then we have printed first element of the list by
mylist[-len(mylist)]
that is"Apple"
. As length of the list is5
somylist[-len(mylist)]
treated asmylist[-5]
.
Note :
If we give index outside the range then it will give IndexError
.
mylist = ["Apple",True,100,"Mango","Banana"]
print(mylist[5])
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_12468/3690712514.py in <module> 1 mylist = ["Apple",True,100,"Mango","Banana"] ----> 2 print(mylist[5]) IndexError: list index out of range
In the above code as the length of the list is 5
so index of last character will be (5-1)=4
. For this reason when we have given index as 5
Python has raised an IndexError
.
Python list is ordered
List items are ordered it means that it maintains a defined order and we can not change it .
Python list is mutable | How to update a list in Python ?
Python list is mutable it means we can change , delete and add items in the list .
Example :
mylist = ["Apple",True,100,"Mango","Banana"]
# Accessing third element before changing
print("Before changing =",mylist[2])
# changing the element
mylist[2]=None
# Accessing third element after changing
print("after changing =",mylist[2])
# printing the list
print(mylist)
Before changing = 100 after changing = None ['Apple', True, None, 'Mango', 'Banana']
- In the above code first we have printed the third element of the list which printed
100
- Then after changing the third element we have again printed that element which printed
None
- At last we have printed the updated list .
Python list allows duplicate values
Python list allows duplicate values it means more than one element in the list can have same value
Example :
mylist = ["Apple",True,100,"Apple","Banana"]
print(mylist)
['Apple', True, 100, 'Apple', 'Banana']
In the above code we can see that Python list has accepted duplicate values .
Slicing in Python List
We can slice one or more element from a list using its index .
Syntax of Slicing
object[start : stop : step]
Parameters of Slicing
- start = Optional , start specifies index number from where slicing will start . Default value is
0
. - Stop = Optional , stop specifies index number at where slicing will end but this number is excluded . Default value is
(length of the object)
. - step = Optional , An integer number which specifies the incrementation . Default is
1
Return type of Slicing
It returns a copy of the given datatype .
Example 1:
mylist = ["Apple",True,100,"Mango","Banana"]
# if nothing is given
# it will print the full list
print("mylist[::] =",mylist[::])
# slicing 2nd element to 3rd element
print("mylist[1:3] =",mylist[1:3])
# as index of 3rd element is 2 and stop
# parameter is excluded so we need to give
# stop parameter as 2+1=3
# if start parameter is not given
# then python will take it as 0
print("mylist[:3] =",mylist[:3])
# if stop parameter is not given
# then python will take it as len(mylist)-1
print("mylist[2:] =",mylist[2:])
# if we want to print 1st ,3rd and 5th character
# then we need to give step parameter as 2
print("mylist[0:5:2] =",mylist[0:5:2])
# by default python takes step parameter as 1
mylist[::] = ['Apple', True, 100, 'Mango', 'Banana'] mylist[1:3] = [True, 100] mylist[:3] = ['Apple', True, 100] mylist[2:] = [100, 'Mango', 'Banana'] mylist[0:5:2] = ['Apple', 100, 'Banana']
In the above code we have seen various examples about slicing of list in Python
Example 2:
mylist = ["Apple",True,100,"Mango","Banana"]
# slicing using negative indexing
# slicing 2nd last character to 3rd last character
print("mylist[-2:-4:-1] =",mylist[-2:-4:-1])
# as index of 3rd last character is -3 and stop
# parameter is excluded so we need to give
# stop parameter as -(3+1)=-4
# but to go -2 to -4 we need to give step as -1
# if we want to print last ,3rd last and 5th last character
# then we need to give step parameter as 2
print("mylist[-1:-6:-2] =",mylist[-1:-6:-2])
mylist[-2:-4:-1] = ['Mango', 100] mylist[-1:-6:-2] = ['Banana', 100, 'Apple']
Note :
When we use negative step parameter then default value of start and stop parameter becomes -1
and -(length of the object)
.
Example :
mylist = ["Apple",True,100,"Mango","Banana"]
# when start and stop parameter both is not given
# python takes start and stop as -1 and -5
print("mylist[::-1] =",mylist[::-1])
# in this example we just reverse the list
# when stop parameter is not given python takes stop as -5
print("mylist[2::-1] =",mylist[2::-1])
# when start parameter is not given python takes start as -1
print("mylist[:3:-1] =",mylist[:3:-1])
mylist[::-1] = ['Banana', 'Mango', 100, True, 'Apple'] mylist[2::-1] = [100, True, 'Apple'] mylist[:3:-1] = ['Banana']
How to delete a list in Python ?
We can delete a list in Python using del
keyword . But if we want to access the list after deleting it using del
keyword it will raise a NameError
.
Example :
mylist = ["Apple",True,100,"Mango","Banana"]
# printing the list before deleting
print(mylist)
# delete the list
del mylist
# # printing the list after deleting
print(mylist)
['Apple', True, 100, 'Mango', 'Banana']
--------------------------------------------------------------------------- NameError Traceback (most recent call last) C:\Users\RAJKUM~1\AppData\Local\Temp/ipykernel_12468/2244030005.py in <module> 8 9 # # printing the list after deleting ---> 10 print(mylist) NameError: name 'mylist' is not defined
Iterating a list in Python
We can iterate a list in Python using for-loop
and while-loop
.
Example 1:
# for loop with list as iterator
mylist = ['Apple', True, 100, 'Mango', 'Banana']
for element in mylist:
print(element)
Apple True 100 Mango Banana
In the above code we have iterated all element from mylist
using for-loop
.
Example 2:
# python while loop with list datatype
mylist = ['Apple', True, 100, 'Mango', 'Banana']
number=0
while number < len(mylist):
print(mylist[number])
number+=1
Apple True 100 Mango Banana
In the above code we have iterated all element from mylist
using while-loop
To know about len()
function click here .
Nested List in Python
When we use list inside a list then it is called Nested list . Earlier we have seen that list items can be of any datatype . So list item can be a list .
Example :
# nested list in python
mylist = ['Apple', True, 100, 'Mango', 'Banana',["Rajkumar","sourav"]]
print(mylist)
['Apple', True, 100, 'Mango', 'Banana', ['Rajkumar', 'sourav']]
In the above code we have seen that Python accepts a list as list item .
Thank you for reading this Article . If You enjoy it Please Share the article . If you want to say something Please Comment .