0% found this document useful (0 votes)
30 views29 pages

List

The document provides an overview of Python lists, including their creation, accessing elements, slicing, and various operations and functions. It explains the mutability of lists, methods for modifying them, and the differences between shallow and deep copies. Additionally, it includes practice questions and exercises for applying the concepts learned.

Uploaded by

srisandhiya553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views29 pages

List

The document provides an overview of Python lists, including their creation, accessing elements, slicing, and various operations and functions. It explains the mutability of lists, methods for modifying them, and the differences between shallow and deep copies. Additionally, it includes practice questions and exercises for applying the concepts learned.

Uploaded by

srisandhiya553
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Programming in Python

(Data Type: List)

Dr. Faisal Anwer


Department of Computer Science
Aligarh Muslim University 1
Copyright © Dept of Computer Science, AMU, Aligarh. Permission required for reproduction or display.
Recap
• Creating String variable

• Accessing String

• String Slicing

• Operations & Functions of String


Contents
• Creating List variable

• Accessing List

• List Slicing

• Operations & Functions of List

• List Cloning/Copy
Python Lists
 A list is a sequence of data values called items or elements. The items in
a list need not be of the same type.

 It is a mutable data type.

Creating a List
 The list is defined as a list of comma-separated values (items) in square
brackets.

 List can also be created using list() function


Example
 List2 = [„Physics‟, „Chemistry‟, 10, 30, 20.5]
 List3 = [[1,2], 4, 5]
 List4 = []
 List5 = list(string/tuple/dict/)
Lists: Accessing Elements
 Each item in a list has a unique index that specifies its position.

 The list index can be either positive or negative


 Positive index starts from the left of the list and ranges from 0 to
(length of the list) minus 1.

 Negative index starts from the right side of the list and ranges
from -1 to minus length of the list (i.e. –length ).

 Example
 List2= [[1,2], 4, 5]
#Accessing Elements
-List2[0], List2[1], List2[2], List2[0][0], List2[0][1]
Creating List Using List Function
The range function returns a list of numbers that range from zero to
one less than the parameter.

 Example:
 list( range(4) ) ------[0, 1, 2, 3]
 list( range(1, 4) ) ------[1, 2, 3]
 list( range(2, 10, 2) ) ------[2, 4, 6, 8]
 list( range(-1, -11, -2) ) ------[-1, -3, -5, -7, -9]
Lists: Operations & Functions
Python-Sequences

Common Common
Operations Functions

Slicing Concatenate len() min() & max()

Membership Repeat Index() Count()


List Slices
 A slice is a list consisting of elements of the given list.

 Slicing uses three index values low, high and step_value

 Default value is 0 for low, 1 for step_value and (total length -1) for
high.

 List1[low: high] – The sublist starts from the low index and ends at the
index one position before the high.

 Example: List1 = ['a', 'b', 'c', 'd', 'e', 'f']


 List1[1:3]  ['b', 'c']
 List1[:4]  ['a', 'b', 'c', 'd']
 List1[3:]  ['d', 'e', 'f']
 List1[:]  ['a', 'b', 'c', 'd', 'e', 'f‟]
 List1[::2]  ['a', 'c', 'e‟]
 List1[::-1]  ['f', 'e', 'd', 'c', 'b', 'a']
Lists Operations
a = [1, 2, 3]; b = [3, 4, 5, 6, 7 ]

Concatenation (+)
 The concatenation operator concatenates two lists.

Repetition (*)
 The * operator concatenates a list zero or more times.

Membership operators (in/not in)


 The in operator returns true if an element exists in the given list.
 The not in operator returns true if an element does not exists in the
given list.
Lists: Sequence Functions
a = [1, 2, 3]; b = [3, 4, 5, 6, 7 ]

len() – len(a)
Example: len(a) returns 3

min() & max() --- min(a) & max(a)


Example: min(a) returns 1

isinstance(object, type) --- The isinstance() function returns True


if the specified object is of the specified type, otherwise False.
Lists: Methods
 The methods behave like a function but have a slightly different
syntax.
 A method is always called with a given data value(known as
object), which is placed before the method name in the call.

 The syntax of a method call is:


Object_name.method_name(arg1, arg2, ….)

 The methods may also expect arguments and return values.


Lists: Methods
a = [1, 2, 3,4, 5], b = [10, 11, 12, 13], c = [20, 1, -2, 13]

 reverse: [A.reverse()]: It reverses elements of the list in place.


Example- a.reverse()  [5, 4, 3, 2, 1]

 sort: [A.sort()]: It sorts objects of the list in place.


Example- c.sort()  [-2, 1, 13, 20]

 extend: [A.extend()]: Extend list by appending elements from


the iterable.
Example- a.extend(b)  [1, 2, 3, 4, 5, 10, 11, 12, 13]
List: Methods
• clear:[A.clear()]: Removes all elements from the list A.

• copy: [A.copy()]: Returns a copy of the list A.

• count: [A.count(obj)]: It returns count of how many times element


obj occurs in list A.

• index : [A.index(obj) ]: It returns the lowest index in list Athat


element obj appears first time.
List: Methods
• insert :[A.insert(index, obj)]: Insert object at index.

• append :[A.append(obj)]: Insert object at last.

• remove :[A.remove(obj)]: Remove first occurrence of obj.


List is mutable
 Strings are "immutable“

 Lists are "mutable"


 The elements can be inserted, removed, or replaced
 Index (Slice) operator to replace the value of an element
(elements)
 Insert/append/extend methods can be used to insert elements
 Remove/clear methods can be used to remove elements
List is mutable
 List update/Replace
 The single or multiple elements of lists can be updated.
 To update a single element, use the index.
 To update multiple elements,
 The slice operator can be used on the left side of an assignment
operator
 Use the index of the multiple elements and subscript operator
on the left-hand side of the assignment operator.
 Example:
 List1 = ['a', 'b', 'c', 'd', 'e', 'f']
 List1[2] = ‘z’  List1 -- ['a', 'b', ‘z', 'd', 'e', 'f']
 List1[1:3] = ['x', 'y‟]  List1 -- ['a', 'x', 'y', 'd', 'e', 'f‟]
 List1[1], List1[2] = 12, 23  List1 – ['a‟, 12, 23, 'd', 'e', 'f‟]
 List1[0:5:2] = [1, 2, 3]  List1 – [1, 'x', 2, 'd', 3, 'f']
List is mutable
 Elements insertion -To append/insert a new element in a list
 append() method: It appends a new element at the end of the list.
 insert() method: It appends a new element into the list at a given
index.
 Extend() method: Extend the list by appending elements from the
iterable (sequence).

 Example:
 List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
 List1.append (20) # Insert 20 at the end of the list
 List1.insert(1, 30) #Insert 30 at the index 1
 List1.extend([10, 11, 12])
List is mutable
 Elements Removal -To remove an element from the list
 Remove() method – If you do not know the index of the element to
be deleted.
 Pop() method-Remove last element by default or the element for
which the index is mentioned.
 Clear() method –Remove all elements of the list. It returns the
empty list.
 Example:
 List1 = ['a', 'b', 'c', 'd', 'e', 'f']
 del (List1[2]) # Remove third element
 del(List1) #Remove complete list
 List1.remove(„d‟) #Remove element with value d
 List1.pop() #Remove Last element
 List1.pop(3) # Remove element at index 3
 List1.clear() # remove all elements of list
Accessing Elements of List Through Loop

friends = ['Joseph', 'Glenn', 'Sally']


for friend in friends :
print('Happy New Year:', friend)

for i in range(len(friends)) :
friend = friends[i]
print('Happy New Year:', friend)
List Cloning/Copy
Cloning: The process to make a copy of the list to modify it in
future while keeping the original one.

Three Ways of Cloning/Copy-


1. Creating Reference using assignment Operator (Shallow Copy)

2. Creating Clone using Slice Operator (Shallow Copy)


• The easiest way to clone a list A is to use the slice operator
i.e., A[:].
• Taking any slice creates a new list.

3. Creating Clone using copy method (Deep Copy)


Shallow Copy & Deep Copy
The assignment statement creates a reference to an existing
object. They do not create copies of objects.

A = [55, [40, 15, 70], 7, 8, 'a‟ ]


B=A

For working with mutable objects, anyone may be interested to


create “real copies” or “clones” of these objects so that they can
modify the clone without modifying the original at the same time.
Shallow Copy & Deep Copy

Old_List = [[11, 23, 34], [40, 15, 70], 7, 8, 'a‟ ] #Creates a nested list
New_List = Old_List[:] # Creates new LIST
new_list[1][2] = 9
print('Old List:‟, Old_List)
print('ID of Old List:', id(Old_List))
print('New List:‟, New_List)
print('ID of New List:', id(New_List))

If you update any value(NESTED value) in New_List or Old_List, the


changes are visible in both.

Essentially, It is required to have the original values unchanged and only


modify the new values or vice versa.
Shallow Copy & Deep
Copy
 A shallow copy constructs a new compound object and then
inserts references into it to the objects found in the original.

 A deep copy constructs a new compound object and then,


recursively, inserts copies into it of the objects found in the
original.

 Copy Module is used to create these copies (shallow and deep


copies)

import copy
copy.copy(x)  Returns a shallow copy of x (It is almost similar to the
assignment or slice operator for nested objects)

 copy.deepcopy(x), Returns a deep copy of x.


Shallow Copy
import copy
Old_List = [[10, 20, 30], [14, 50, 64], [77, 89, 90]]
New_List = copy.copy(Old_List) #Create new and dependent object with
same content
print("Old list with ID :", Old_List, id(Old_List))
print("New list with ID:", New_List, id(New_List))

Old_List.append([14, 2, 4]) #Appending a list to Old_List


print("Old list with ID :", Old_List, id(Old_List) )#Changes visible in Old
List not in New List
print("New list with ID:", New_List, id(New_List))

Old_List[1][1] = 'AA'
print("Old list with ID :", Old_List, id(Old_List))
print("New list with ID:", New_List, id(New_List))
Deep Copy
 A deep copy creates a new object and recursively adds the copies of
nested objects present in the original elements.

 The deep copy creates independent copy of original object and all
its nested objects.

Example
import copy
old_list = [[1, 1, 1], [2, 2, 2], [3, 3, 3]]
new_list = copy.deepcopy(old_list) #Creates an independent copy
print("Old list:", old_list)
print("New list:", new_list)
old_list[1][0] = 'BB‟ # This change will reflect only in Old
List
print("Old list:", old_list)
print("New list:", new_list)
Practice Questions

1. Given a list containing strings and integers. Write


a program to create two separate lists consisting of
strings and integers respectively.

2. Write Python Program to Sort Words in Alphabetic


Order
Solution
List1 = ["hello", 2, 3, 4, "this", 5, 6, 7, "is"]

#Creating empty list


IntegerList = []
StringList = []

#adding elements to list


for element in List1:
if isinstance(element, int) == True:
IntegerList.append(element)
if isinstance(element, str) == True:
StringList.append(element)

# display the sorted words


print("The list of integers is:", IntegerList.sort())
print("The list of strings is:", StringList.sort())
Exercises
 Write programs in python for the following:
1. Read a list and transfer even and odd integers into Two
Different Lists.
2. Merge Two Lists and Sort it.
3. Find the Second Largest Number in a List and all its index.
4. Sort a List According to the Length of the Elements
5. Create a List of Tuples with the First Element as the Number
and Second Element as the Square of the Number
6. Remove the Duplicate Items from a List
7. Find Element Occurring Odd Number of Times in a List
8. Read a List of Words and Return the Length of the Longest
One
Summary
• Creating List variable

• Accessing List

• List Slicing

• Operations & Functions of List

• List Cloning/Copy

You might also like