You are on page 1of 53

UNIT-3

LIST
LIST
■ A Python list is an ordered and changeable collection of data objects. Unlike an array,
which can contain objects of a single type, a list can contain a mixture of objects
■ The list is a most versatile datatype available in Python which can be written as a list of
comma-separated values between square brackets [].
■ Important thing about a list is that items in a list need not be of the same type.
■ For example −
■ list1 = [‘physics’, ‘chemistry’, 1997, 2000];
■ list2 = [1, 2, 3, 4, 5 ];
list3 = [“a”, “b”, “c”, “d”]
Accessing Values in Lists
To access values in lists, use the square brackets for slicing along with the index or indices to
obtain value available at that index.
EXAMPLE
List1 = [‘physics’, ‘chemistry’, 1997, 2000];
list2 = [1, 2, 3, 4, 5, 6, 7 ];
print “list1[0]: “, list1[0]
print “list2[1:5]: “, list2[1:5]
OUTPUT
List1[0]: physics
list2[1:5]: [2, 3, 4, 5]
Updating Lists
You can update single or multiple elements of lists by giving the slice on the left-hand side of the
assignment operator, and you can add to elements in a list with the append() method
EXAMPLE
List = [‘physics’, ‘chemistry’, 1997, 2000];
print “Value available at index 2 : “
print list[2]
list[2] = 2001;
print “New value available at index 2 : “
print list[2]
OUTPUT
Value available at index 2 : 1997
New value available at index 2 : 2001
■ If you like to add a single element to the python list then list.append(value) is the best fit
for you. The list.append(value) always adds the value to the end of existing list.
EXAMPLE
A_list = [1, 2, 3, 4]
a_list.append(5)
print(a_list)
OUTPUT
[1, 2, 3, 4, 5]
Nested list
■ A nested list in python allows a list to contain multiple sublists within itself.
■ Each sublist can have items of different data types.
■ It can be created by placing comma-separated sublists and items together.
■ A list can contain any sort object, even another list (sublist), which in turn can contain
sublists themselves, and so on. This is known as nested list.
■ Create a Nested List
■ A nested list is created by placing a comma-separated sequence of sublists.
L = [‘a’, [‘bb’, [‘ccc’, ‘ddd’], ‘ee’, ‘ff’], ‘g’, ‘h’]
Access Nested List Items by Index
■ You can access individual items in a nested list using multiple indexes.
■ The indexes for the items in a nested list are illustrated as below:
Example

L = [‘a’, ‘b’, [‘cc’, ‘dd’, [‘eee’, ‘fff’]], ‘g’, ‘h’]


print(L[2])
# Prints [‘cc’, ‘dd’, [‘eee’, ‘fff’]]
print(L[2][2])
# Prints [‘eee’, ‘fff’]
print(L[2][2][0])
# Prints eee
Change Nested List Item Value
You can change the value of a specific item in a nested list by referring to its index number.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1][1] = 0
print(L)
# Prints [‘a’, [‘bb’, 0], ‘d’]
Add items to a Nested list
*To add new values to the end of the nested list, use append() method.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1].append(‘xx’)
print(L)
# Prints [‘a’, [‘bb’, ‘cc’, ‘xx’], ‘d’]
*When you want to insert an item at a specific position in a nested list, use insert() method.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’], ‘d’]
L[1].insert(0,’xx’)
print(L)
# Prints [‘a’, [‘xx’, ‘bb’, ‘cc’], ‘d’]
Remove items from a Nested List
■ If you know the index of the item you want, you can use pop() method. It modifies the list and returns the removed item.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’, ‘dd’], ‘e’]
x = L[1].pop(1)
print(L)
# Prints [‘a’, [‘bb’, ‘dd’], ‘e’]
■ If you’re not sure where the item is in the list, use remove() method to delete it by value.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’, ‘dd’], ‘e’]
L[1].remove(‘cc’)
print(L)
# Prints [‘a’, [‘bb’, ‘dd’], ‘e’]
If you don’t need the removed value, use the del statement.
EXAMPLE
L = [‘a’, [‘bb’, ‘cc’, ‘dd’], ‘e’]
del L[1][1]
print(L)
# Prints [‘a’, [‘bb’, ‘dd’], ‘e’]
Cloning list
In some operations in Python, you may need to copy the contents of a list. In this article, we will look at the different ways of
copying or cloning the contents of a list.
To copy or clone a list in Python, the following methods can be used:

= operator method
copy() method
slice() method
list() method
deepcopy() method
copy.copy() shallow copy method
comprehension method
■ extend() method
1list copy using =(assignment operator)
This is the simplest method of cloning a list by using = operators. This operator assigns the old list to the
new list using Python = operators.
■ Here we will create a list and then we will copy the old list into the new list using assignment operators
EXAMPLE.
My_list = [1, 2, 3, 4, 5]
copy_list = my_list
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [1, 2, 3]
New List: [1, 2, 3]
2.Copy list using copy() method

The Python List copy() is an inbuilt method copy used to copy all the elements from one list to another.
EXAMPLE
My_list = [1, 2, 3, 4, 5]
copy_list = my_list.copy()
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [1, 2, 3, 4, 5]
New List: [1, 2, 3, 4, 5]
3.Copy list using the List slice method
■ This is the easiest and fastest way to clone a list.
■ This method is considered when we want to modify a list and also keep a copy of the original.
■ In this, we make a copy of the list itself, along with the reference. This process is also called cloning.
EXAMPLE
My_list = [1, 2, 3, 4, 5]
copy_list = my_list[:]
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [1, 2, 3, 4, 5]
New List: [1, 2, 3, 4, 5]
4.Copy list using list() method
■ The list() method is considered the simplest method of cloning list items.
■ This function creates a list object
■ Any list object is a collection of elements that have a specific order.
■ The built-in function takes only one parameter called iterable.
■ This can be a sequence such as a tuple or string. It can also be a collection or an iterator
object.
■ The list() method is a constructor that returns a sequence of list elements that you can
modify
Example
My_list = [1, 2, 3, 4, 5]
copy_list = list(my_list)
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [1, 2, 3, 4, 5]
New List: [1, 2, 3, 4, 5]
5.Copy list using the deep copy method
■ A deep copy creates a new compound object before inserting copies of the items found
in the original into it in a recursive manner.
■ It means first constructing a new collection object and then recursively populating it
with copies of the child objects found in the original.
■ In the case of deep copy, a copy of the object is copied into another object. It means that
any changes made to a copy of the object do not reflect in the original object.
Example
# importing copy module
import copy
# initializing list 1
li1 = [1, 2, [3,5], 4]
# using deepcopy for deepcopy
li3 = copy.deepcopy(li1)
print(li3)
Output:
[1, 2, [3, 5], 4]
6.Copy list using the shallow copy
method
■ The shallow copy method creates a new collection object.
■ The method then populates the object with references to the original elements.
■ The process is not recursive, and no copies of the nested objects are created.
■ Here, a reference of one object is copied into another.
■ Thus changes in the copy will not affect the original
Example
Import copy
# Declare recursive list
my_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
# Copy list using copy() method
copy_list = copy.copy(my_list)
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
New List: [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
7.Copy list using list comprehension
method
■ This method is used for copying items of a list to another list.
■ In this method, a new list is created from another list or a string.
■ This resultant list is created using a for statement and conditional statements.
■ Example:
■ my_list = []
■ for letter in ‘Stechies’:
■ my_list.append(letter)
■ print(‘New List: ‘, my_list)
■ Output:
New List: [‘S’, ‘t’, ‘e’, ‘c’, ‘h’, ‘I’, ‘e’, ‘s’]
8.Copy list using extend() method
■ In the extend method, the elements of one list are copied into another list by adding them at the end.
■ The method takes in a single parameter that is a list.
■ The elements in this argument are added to the original list.
■ Elements of native data types such as a set or a tuple can also be passed as arguments.
EXAMPLE
My_list = [1, 2, 3, 4, 5]
copy_list = []
copy_list.extend(my_list)
print(‘Old List: ‘, my_list)
print(‘New List: ‘, copy_list)
Output:
Old List: [1, 2, 3, 4, 5]
New List: [1, 2, 3, 4, 5]
Basic List Operations
The concatenation (+) and repetition (*) operators work in the same way as they were
working with the strings.
The different operations of list are

Repetition
Concatenation
Length
Iteration
■ Membership
Repetition
The repetition operator enables the list elements to be repeated multiple times.
Code
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
Concatenation
It concatenates the list mentioned on either side of the operator.
Code
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
Length
It is used to get the length of the list
Code
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:
9
Iteration
The for loop is used to iterate over the list elements.
Code
list1 = [12, 14, 16, 39, 40]
# iterating
for I in list1:
print(i)
Output:
12
14
16
39
40
Membership
It returns true if a particular item exists in a particular list otherwise false.
Code
list1 = [100, 200, 300, 400, 500]
print(600 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
Output:
False
False
True
True
List methods

Python List Methodshas multiple methods to work with Python lists, Below we’ve
explained all the methods you can use with Python lists, for example, append(), copy(),
insert() and more.
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list
Using List as Stack

■ Stack works on the principle of “Last-in, first-out”.


■ Also, the inbuilt functions in Python make the code short and simple.
■ To add an item to the top of the list, i.e., to push an item, we use append() function and to pop out an element we
use pop() function.
■ These functions work quiet efficiently and fast in end operations
■ Characteristics of Stack

Insertion order is preserved.


Duplicacy is allowed in Stack.
Similar data-type Storage.
■ Highly useful in Parsing Operations
Example

stack = [“Amar”, “Akbar”, “Anthony”]


stack.append(“Ram”)
stack.append(“Iqbal”)
print(stack)
print(stack.pop())
print(stack)
print(stack.pop())
print(stack)
Output

Output:
[‘Amar’, ‘Akbar’, ‘Anthony’, ‘Ram’, ‘Iqbal’]
Iqbal
[‘Amar’, ‘Akbar’, ‘Anthony’, ‘Ram’]
Ram
[‘Amar’, ‘Akbar’, ‘Anthony’]
Using queue in lists
■ Queue works on the principle of “First-in, first-out”. Below is list implementation of
queue.
■ We use pop(0) to remove the first item from a list.
Characteristics of Queue
Insertion order is preserved.
Duplicacy is allowed in Queue.
Similar data-type Storage.
■ Highly useful in Parsing CPU task operations
Example
Queue = [“Amar”, “Akbar”, “Anthony”]
queue.append(“Ram”)
queue.append(“Iqbal”)
print(queue)
print(queue.pop(0))
print(queue)
print(queue.pop(0))
print(queue)
Output
[‘Amar’, ‘Akbar’, ‘Anthony’, ‘Ram’, ‘Iqbal’]
Amar
[‘Akbar’, ‘Anthony’, ‘Ram’, ‘Iqbal’]
Akbar
[‘Anthony’, ‘Ram’, ‘Iqbal’]
Functional Programming in Python
■ Functional programming is a programming paradigm in which we try to bind everything
in pure mathematical functions style.
■ It is a declarative type of programming style.
■ Its main focus is on “what to solve” in contrast to an imperative style where the main
focus is “how to solve“.
■ It uses expressions instead of statements.
■ An expression is evaluated to produce a value whereas a statement is executed to assign
variables.
Concepts of Functional Programming
Pure Functions
■ These functions have two main properties. First, they always produce the same output
for the same arguments irrespective of anything else. Secondly, they have no side-
effects i.e. they do modify any argument or global variables or output something.
■ The second property is also known as immutability.
■ The only result of the Pure Function is the value it returns
■ Programs done using functional programming are easy to debug because pure functions
have no side effects or hidden I/O
Example
Def pure_func(List):
New_List = []
for I in List:
New_List.append(i**2)
return New_List
Original_List = [1, 2, 3, 4]
Modified_List = pure_func(Original_List)
print(“Original List:”, Original_List)
print(“Modified List:”, Modified_List)
Output:
Original List: [1, 2, 3, 4]
Modified List: [1, 4, 9, 16]
Recursion
■ There are no “for” or “while” loop in functional languages. Iteration in functional
languages is implemented through recursion.
■ Recursion is a process in which a function calls itself directly or indirectly.
■ In the recursive program, the solution to the base case is provided and the solution to the
bigger problem is expressed in terms of smaller problems.
■ The base case can be considered as a condition that tells the compiler or interpreter to
exit from the function.
Example
Def Sum(L, I, n, count):
if n <= i:
return count
count += L[i]
count = Sum(L, I + 1, n, count)
return count
L = [1, 2, 3, 4, 5]
count = 0
n = len(L)
print(Sum(L, 0, n, count))
Output:
15
Functions are First-Class and can be
Higher-Order
■ First-class objects are handled uniformly throughout. They may be stored in data structures, passed as
arguments, or used in control structures.
■ A programming language is said to support first-class functions if it treats functions as first-class objects.
■ Properties of first class functions:

A function is an instance of the Object type.


You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
■ You can store them in data structures such as hash tables, lists, …
Example

Def shout(text):
return text.upper()
def whisper(text):
return text.lower()
def greet(func):
greeting = func(“Hi, I am created by a function passed as an argument.”)
print(greeting)
greet(shout)
greet(whisper)
Output:
HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.
Hi, I am created by a function passed as an argument
Built-in Higher-order functions
■ To make the processing of iterable objects like lists and iterator much easier, Python has
implemented some commonly used Higher-Order Functions.
■ These functions return an iterator that is space-efficient. Some of the built-in higher-
order functions are:
■ Map(): map() function returns a list of the results after applying the given function to
each item of a given iterable (list, tuple etc.)
■ Filter(): The filter() method filters the given sequence with the help of a function that
tests each element in the sequence to be true or not.
Map()
Syntax: map(fun, iter)
Parameters:
fun: It is a function to which map passes each element of given iterable.
Iter: It is a iterable which is to be mapped.
Return Type: Returns an iterator of map class.
Example
def addition(n):
return n + n
numbers = (1, 2, 3, 4)
results = map(addition, numbers)
print(result)
For result in results:
print(result, end = " ")
Output:
<map object at 0x7fae3004b630>
246
Filter()
Syntax: filter(function, sequence)
Parameters:
function: a function that tests if each element of a sequence true or not.
Sequence: sequence which needs to be filtered, it can be sets, lists, tuples, or containers of
any iterators.
Return Type: returns an iterator that is already filtered.
Example
Def fun(variabl):
letters = [‘a’, ‘e’, ‘I’, ‘o’, ‘’]
if (variable in letters):
return True
else:
return False
sequence = [‘g’, ‘e’, ‘e’, ‘j’, ‘k’, ‘s’, ‘p’, ‘r’]
filtered = filter(fun, sequence)
print(‘The filtered letters are:’)
for s in filtered:
print(s)
Output:
The filtered letters are:
e
Lambda functions:
■ In Python, anonymous function means that a function is without a name.
■ As we already know that def keyword is used to define the normal functions and the lambda keyword is
used to create anonymous functions.
Syntax:
Lambda arguments: expression
1) This function can have any number of arguments but only one expression, which is evaluated and returned.
2) 2) One is free to use lambda functions wherever function objects are required.
3) You need to keep in your knowledge that lambda functions are syntactically restricted to a single
expression.
4) It has various uses in particular fields of programming besides other types of expressions in functions.
Example
cube = lambda x: x * x*x
print(cube(7))
L = [1, 3, 2, 4, 5, 6]
is_even = [x for x in L if x % 2 == 0]
print(is_even)
Output:
343
[2, 4, 6]
Immutability
■ Immutability is a functional programming paradigm can be used for debugging as it will throw an
error where the variable is being changed not where the value is changed.
■ Python too supports some immutable data types like string, tuple, numeric, etc.
EXAMPLE
Immutable = “GeeksforGeeks”
immutable[1] = ‘K’
Output:
Traceback (most recent call last):
File “/home/ee8bf8d8f560b97c7ec0ef080a077879.py”, line 10, in
immutable[1] = ‘K’
TypeError: ‘str’ object does not support item assignment

You might also like