Python Lists
In
this lecture, we will master all about python list, the important features of
the list, list creation, list manipulation using slicing operator, various list
operations, and so on with the help of examples. Also, we will learn about the nested
list.
Among
the compound datatypes in python, List is the most versatile and commonly used
datatype. A list is a sequence-based datatype with a collection of
objects. The objects can be of any type.
Key Features of Python List
- List are mutable in nature
- List maintains the order of the objects
- List supports indexing
- The list can be heterogeneous
- List is dynamic
- The list allows duplicate values
- The list can be nested
How to define a Python List
In
python, the List is defined by encasing a sequence of elements in a square
bracket [ ]. Each element is separated using commas. The list can
embrace any number of elements and can be of any type. The following example
would help you to understand how a list is defined in python.
Empty
list: A
List with no elements or of length 0.
Example: Defining an empty list
emp_list =[]
Homogenous
list: A list with elements of the same datatype.
Example: Defining a homogenous list
with integer elements
int_list =[10,20,30]
.
Heterogeneous
or Mixed List: A
list with elements of different data types
Example: Defining a mixed list with
String, Integer, and Float type elements.
mix_list =['Tom',25,5.9]
Nested
List: A
List containing another list.
Example: Defining a nested List
Nest_List = [['Apple',
'Apricot'],['Banana','Blueberry'],"Cherry"]
Indexing & Slicing to access List Items
Like
String, items in a list can be accessed either using index [] operator or slicing
operator [:].We can consider a list as a
dynamic array and so indexing and slicing work well with a python list.
Indexing in python List
Indexing
is the process of assigning a number to items in a list for easy access. The
index always starts with zero and must be an integer.
Two types of indexing in the python list are :
- Positive Indexing – indexing starts with 0
and traverses in a forward direction from head to tail.
- Negative Indexing – indexing starts with -1
and traverses in the backward direction from tail to head.
To
understand thoroughly about indexing let’s consider the example and its
visualization. ‘LIST’ is a python list consisting of elements ‘RED’, ‘BLUE’,’
GREEN’ & PINK. Each element in the list is assigned with a number
corresponding to their position based on positive and negative indexing as
shown below.
1. Getting elements through Positive
indexing
It is possible to access the individual items from a list by
referring to its index number. The below code shows how to access an item using
positive indexing.
Example: Getting items through
positive indexing
List = ['Red','Blue','Green','Pink']
print("List[0]=",List[0])
print("List[3]=",List[3])
Output:
List[0]= Red
List[3]= Pink
2. Getting elements through Negative
indexing
Python list also supports negative indexing to access items
from the tail of a list. Negative indexing always starts from the end of the
list with index -1.
Example: Getting items through
negative indexing
List = ['Red','Blue','Green','Pink']
print("List[-1]=",List[-1])
print("List[-3]=",List[-3])
Output:
List[-1]= Pink
List[-3]= Blue
Slicing in Python List
Python
List also works well with range slice operator [:].Here,
using the slice operator we can slice chunks of items from a list as needed. In
short, we can create a sublist using the slice operator. The syntax for Range
Slice is
L [ m:n]
where
L is the list containing the items
m: starting index
n: ending index
L[m:n] returns the sublist from the index m to n, but excluding the
index n.
Slicing itself can be done in various ways with positive and negative indexing.
Slicing can be best expressed by placing the items in the middle of indices as
illustrated below.
1. List Slicing through positive
indexing
o Slicing of the form :L[m:n] returns the sublist from
position m to n, but excluding index n.
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[1:3] =",L[1:3])
Output:
L[1:3] = ['Blue', 'Green']
o Slicing of the form :L[:n] returns the sublist from
starting position by default to n, but excluding index n.
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[:2] =",L[:2])
Output:
L[:2] = ['Red', 'Blue']
o Slicing of the form :L[m:] returns the sublist from
the position m to the ending index.
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[2:] =",L[2:])
Output:
L[2:] = ['Green', 'Pink', 'Grey']
2. List Slicing through negative
indexing
o Slicing of the form :L[-m:-n] returns the sublist from
position m to n, but excluding index n.
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[-4:-2] =",L[-4:-2])
Output:
L[-4:-2] = ['Blue', 'Green']
o Slicing of the form :L[:n] returns the sublist
from starting position by default to n, but excluding index n
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[:-2] =",L[:-2])
Output:
L[:-2] = ['Red', 'Blue', 'Green']
o Slicing of the form :L[-m: ] returns the sublist from
the position m to the ending index.
o
L = ['Red','Blue','Green','Pink','Grey']
o
print("L[-4:] =",L[-4:])
Output:
L[-4:] = ['Blue', 'Green', 'Pink', 'Grey']
How to modify Python List
One
of the prominent features that make List a versatile datatype in the python
programming language is that “ List are Mutable”. That means a list can be
altered after the list has been created. Python List can be modified by adding,
removing, or changing items as needed. Python offers a wide variety of ways to
alter a list.
1. How to Replace items in a Python
List?
Unlike a string, a Python list can be modified by replacing
existing items with other items. Indexing makes it easy to replace an item by
simply reassigning a new item to the position where we need a change using the
assignment operator =. Two possible ways to replace items in a list are:
o Individual item replacement - we are replacing only one
item on the list. In the below example, Red is replaced by Yellow.
o
L = ['Red','Blue','Green','Pink','Grey']
o
L[0]= 'Yellow'
o
print('Modified List is :',L)
Output:
Modified List is : ['Yellow', 'Blue', 'Green', 'Pink',
'Grey']
o Multiple item replacement - we can replace a range of
items in the list. Here, in this instance, Green and Pink is replaced by Orange
and Black respectively
o
L = ['Red','Blue','Green','Pink','Grey']
o
L[2:4]= ['Orange','Black']
o
print('List after modificaiton is',L)
Output:
List after modificaiton is ['Red', 'Blue', 'Orange',
'Black', 'Grey']
2. How to Add items to a Python list?
Yet another way of modifying the
list So additional elements to an existing list. For adding items to a list
python has two methods:
o append() the method is used to add one item
to a python list. The syntax is list_name.append(item)
o
LF =['Daisy','Rose']
o
LF.append('Tulip')
o
print("List after appending:",LF)
Output:
List after appending: ['Daisy', 'Rose', 'Tulip']
o extend() method is used to add a range
of items to a python list. The syntax is list_name.extend([item1,
item2,…])
o
LF =['Daisy', 'Rose', 'Tulip']
o
LF.extend(['Orchid','Poppy'])
o
print("Extend List is:",LF)
Output:
Extend List is: ['Daisy', 'Rose', 'Tulip', 'Orchid',
'Poppy']
o Moreover, an existing list can be
modified by inserting items at a specific location. insert() method is used to insert
a particular item at a distinct position in a list. The insert method takes two
parameters one for specifying the position and the other for the item. The
syntax of insert() is list_name.insert(index,
item)
In the below example, item 20 is inserted at position LN[2].
LN =[ 10,30]
LN.insert(2,20)
print(LN)
Output:
[10, 30, 20]
3. How to Delete items from a Python
list?
So far we have seen the replacement
and addition of items in a list, similarity we can delete items from a list.
Two common methods to delete items from a list are listed below.
o Using keyword del : To delete a known item from the
existing list or to delete the entire list itself. The syntax is del variable_name
o
L = ['Red','Blue','Green','Pink','Grey']
o
del L[2];
o
print(" List after deleting item at index 2
is:",L)
o
Output:
List after deleting item at index 2 is: ['Red', 'Blue',
'Pink', 'Grey']
o Using remove() method: To remove an item from the
existing list. The syntax is List_name.remove(item_name).
o
L = ['Red','Blue','Green','Pink','Grey']
o
L.remove('Blue')
o
print("List after removing item : Blue is:",L)
o
Output:
List after removing item
Blue is: ['Red', 'Green', 'Pink', 'Grey']
o Using pop() method: Removes the items at the provided
index if the index is given otherwise by default removes and returns the last
item. The syntax is List_name.pop(index) .
o
L=[10, 20, 30, 40, 50]
o
L.pop(1);
o
print("List after removing item at index 1 is
:",L)
o
L.pop();
o
print("List after removing the last item is:",L)
Output:
List after removing item at index 1 is : [10, 30, 40, 50]
List after removing the last item is: [10, 30, 40]
Python Nested List
So
far we have studied the list and its features. Another important feature of a
list is its ability to nest. So what do you mean by nesting?
Nesting means storing something inside the
other. In python, a nested list is a list containing a list as its element
which in turn contains another list.
A
nested list is created like how we created the list, the only difference is in
the nested list, one or more elements can be a list.
Defining a nested List
Nest_List = [['Apple',
'Apricot'],['Banana','Blueberry'],"Cherry"]
The
nested list can be represented in a hierarchical structure as follows for
better understanding.
How to access items from a nested list
Accessing
items from a nested list is as simple as referring to multiple indexes. We can
either access items using positive indexing or negative indexing.
Accessing items from a nested List
using positive indexing
NL =
['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
print(NL[3])
print(NL[3][1])
print(NL[3][1][0])
print(NL[4])
Output:
['e', ['fff', 'ggg']]
['fff', 'ggg']
fff
h
Accessing items using negative indexing
Let's
refer to the pictorial representation of the negative indexing of the nested
list.
Accessing items from a nested List
using negative indexing
NL =
['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
print(NL[-3])
print(NL[-3][-1])
print(NL[-3][-1][-1])
print(NL[-4])
Output:
['e', ['fff', 'ggg']]
['fff', 'ggg']
ggg
d
How to Modify a Nested List
Similarly,
we can modify the nested list by
1. Altering the values using the
indexing technique
changing items in a Nested List
NL = ['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1][0]= 0
print(NL)
Output:
['a', [0, 'cc'], 'd', ['e', ['fff', 'ggg']], 'h', 'i']
2. Using append() or insert() or
extend() methods.
Adding items in a Nested List
NNL =
['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1].append('xx')
NL[1].insert(0,'yy')
NL[3][1].extend([1,2,3])
print(NL)
Output:
['a', ['yy', 'bb', 'cc', 'xx'], 'd', ['e', ['fff', 'ggg', 1,
2, 3]], 'h', 'i']
3. Removing items using pop() ,or
remove() or del keyword.
Removing items in a Nested List
NL =
['a',['bb','cc'],'d',['e',['fff','ggg']],'h','i']
NL[1].pop(0)
print(NL) #removed items bb
del NL[3][1][0]
print(NL) #removed item fff
NL[3][1].remove('ggg')
print(NL)
Output:
['a', ['cc'], 'd', ['e', ['fff', 'ggg']], 'h', 'i']
['a', ['cc'], 'd', ['e', ['ggg']], 'h', 'i']
['a', ['cc'], 'd', ['e', []], 'h', 'i']
Python List Functions
Python
list has some built-in functions to perform some usual sequential operations.
The basic functions are tabulated below for easy reference.
Function |
Description |
len(List) |
returns the length of the list |
max(List) |
returns the largest value among
the list |
min(List) |
returns the smallest value among
the list |
compare(L1,L2) |
compares items in list L1 with
items in list L2 |
list(seq) |
transforms tuple to a list |
Python List Operators and Operations
As
learned in the string, Python List also has operators to do some specific
operations. The most common operations are given below for better
understanding.
1. Checking Sublist using Membership
operator
A membership operator is used to validate the presence of an
item or a sublist in the list. The corresponding result will a truth value
either True or False. Two membership operators in python are:
o in: returns True if item or sublist is
present in the provided list
o not in: returns True if item or sublist is
absent in the provided list
L =[1,2,3,5,6,8]
print("Validation 3 in List is
",3 in L)
print("Validation 4 not in List
is",4 not in L)
Output:
Validation 3 in List is True
Validation 4 not in List is True
2. Concatenation and Repetition of List
It is also possible to combine two
or more separate lists in python. Combining two or more separate lists is
termed as concatenation whereas repeating a list multiple times is termed as
repetition. The two operators used for concatenation and repetition are:
o The plus operator (+) is also referred to as the
concatenation operator used to join lists
o The star operator (*) is also referred to as a repetition
operator used to repeat a list.
L1= ['Red','Orange']
L2= ['Blue','Green']
print("Concatenated List is
:",L1+L2)
print("Repeated List
is:",L1*3)
Output:
Concatenated List is : ['Red', 'Orange', 'Blue', 'Green']
Repeated List is: ['Red', 'Orange', 'Red', 'Orange', 'Red',
'Orange']
Python List – Built-in Methods
We
are now familiar with some built-in methods like insert(),remove() ,pop() etc. There are few other methods
available in the python programming language that works well with list-objects.
Methods are accessed using a dot operator like list_name.
method_name(parameters).
The
basic methods are given in a table for easy reference.
Methods |
Description |
count(p) |
Returns the count of occurrence of
an item in a list passed as a parameter |
index(p) |
Returns the lowest index of the
item passed as a parameter |
append(p) |
Appends an item passed as a
parameter to the list; Add one item to the tail of the list |
extend(list) |
Extends the list by adding another
list. |
insert(i,p) |
Insert a particular item to a
specified index where i is the index value and p is the particular item |
remove(p) |
Removes an item passed as a
parameter from the list |
pop() |
By default removes the last item
in a list and return the list. |
clear() |
Removes all elements from the list |
sort() |
By default sorts the list items in
ascending order. |
reverse() |
Inverse the order of items in a
list |
copy() |
Returns a shallow or dummy copy of
an existing list. |