SlideShare a Scribd company logo
LIST METHODS
Prepared by
V.Kumararaja, AP/IT
S.Thanga Prasad, AP/CSE
Er.Perumal Manimekalai College of Engineering, Hosur
1
LIST CREATION
A list is created by placing all the items
(elements) inside a square bracket [ ],
separated by commas.
It can have any number of items and they
may be of different types (integer, float,
string etc.).
Example:
list = [1, 2, 3] # list with same data-types
list = [1, "Hello", 3.4] # list with mixed data-types 2
ACCESS ITEMS FROM A LIST
 It can be access in several ways
 Use the index operator [] to access an item
in a list. Index starts from 0. So, a list having
5 elements will have index from 0 to 4.
 Example:
list = ['p','r','o','b','e']
print(list[2]) #Positive Indexing
print(list[-2]) #Negative Indexing
Output
O
b
3
SLICE LISTS
 Accessing a range of items in a list by using
the slicing operator [ ] using (colon :).
 Slicing can be best visualized by considering
the index to be between the elements.
 Example:
list = ['p','r','o','b','e']
print(list[0:4]) #Positive
print(list[-2:-1]) # Negative
Output
['p', 'r', 'o', 'b']
['b']
4
LIST METHODS
 append() - Add an element to the end of the list.
 count() - Returns the count of number of items passed as
an argument.
 extend() - Add all elements of a list to the another list.
 index() - Returns the index of the first matched item.
 insert() - Insert an item at the defined index.
 pop() - Removes and returns an element at the given
index.
 copy() - Returns a shallow copy of the list
 remove() - Removes an item from the list.
 reverse() - Reverse the order of items in the list.
 sort() - Sort items in a list in ascending order.
5
APPEND() METHODS
The append() method adds a single item
to the existing list.
The append() method only modifies the
original list. It doesn't return any value.
The append() method takes a single
item and adds it to the end of the list.
The item can be numbers, strings,
another list, dictionary etc.
Syntax
list.append(item)
6
Example 1: Adding Element to a List
list = ['hi', 'hello']
print('old list: ', list)
list.append('welcome!')
print('Updated list: ', list)
Example 2: Adding List to a List
list = ['hi', 'hello']
print('old list: ', list)
list1=['welcome‘]
list.append(list1)
print('Updated list: ', list)
APPEND() METHODS - PROGRAMS
Output
old list: ['hi', 'hello']
Updated list: ['hi', 'hello‘,'welcome!']
Output
old list: ['hi', 'hello']
Updated list: ['hi', 'hello', ['welcome']]
7
COUNT() METHODS
 Count() method counts how many times an
element has occurred in a list and returns it.
 The count() method takes a single argument:
 element - element whose count is to be
found.
 The count() method returns the number of
occurrences of an element in a list.
 Syntax
list.count(element)
8
Example: Count the occurrence of an element in the list
list = ['h','i','h','o','w','y','o','u','!','!']
print('The count of i is:',list.count('i'))
print('The count of o is:',list.count('o'))
Example 2: Count the occurrence of tuple and list inside the list
list = ['a', ('h', 'i'), ('a', 'b'), [8, 4]]
count = list.count(('a', 'b'))
print("The count of ('a', 'b') is:", count)
count = list.count([3, 4])
print("The count of [3, 4] is:", count)
COUNT() METHODS - PROGRAMS
Output
The count of i is: 1
The count of o is: 2
Output
The count of ('a', 'b') is: 1
The count of [3, 4] is: 0
9
 The extend() extends the list by adding all items of a list
to the end.
 Extend() method takes a single argument (a list) and
adds it to the end.
 This method also add elements of other native
data_types ,like tuple and set to the list,
 Syntax
EXTEND() METHODS
list1.extend(list2)
Note : The elements
of list2 are added to
the end of list1.
list.extend(list(tuple_type)) Note : The elements
of tuple are added to
the end of list1.
10
EXTEND() METHODS - PROGRAMS
Example 1: Using extend() Method
language = ['C', 'C++', 'Python']
language1 = ['JAVA', 'COBOL']
language.extend(language1)
print('Language List: ', language)
Output
Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL']
11
Example 2: Add Elements of Tuple and Set to List
language = ['C', 'C++', 'Python']
language_tuple = ['JAVA', 'COBOL']
language_set = {'.Net', 'C##'}
language.extend(language_tuple)
print('New Language List: ', language)
language.extend(language_set)
print('Newest Language List: ', language)
EXTEND() METHODS - PROGRAMS
Output
New Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL'] Newest
Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL',
'.Net', 'C##']
12
INDEX( ) METHODS
 Index() method search and find given element in
the list and returns its position.
 However, if the same element is present more than
once, index() method returns its smallest/first
position.
 Index in Python starts from 0 not 1.
 The index() method returns the index of the
element in the list.
 The index method takes a single argument:
 element - element that is to be searched.
 Syntax
list.index(element)
13
INDEX( ) METHODS - PROGRAMS
Example 1: Find position of element present in the
list and not present in the list
list = ['h','i','h','o','w','y','o','u','!','!']
print('The count of i is:',list.index('i'))
print('The count of o is:',list.index('o'))
print('The count of o is:',list.index('z'))
Output
The count of i is: 1
The count of o is: 3
ValueError: 'z' is not in list
14
Example 2: Find index of tuple and list inside a list
random = ['a', ('a', 'd'),('a','b'), [3, 4]]
index = random.index(('a', 'b'))
print("The index of ('a', 'b'):", index)
index = random.index([3, 4])
print("The index of [3, 4]:", index)
INDEX( ) METHODS - PROGRAMS
Output
The index of ('a', 'b'): 2
The index of [3, 4]: 3
15
 The insert() method inserts the element to the list at
the given index.
 The insert() function takes two parameters:
 index - position where element needs to be
inserted
 element - this is the element to be inserted in
the list
 The insert() method only inserts the element to the list.
It doesn't return any value.
 Syntax
INSERT( ) METHODS
list.insert(index, element) 16
Example 1: Inserting Element to List
vowels=['a','i','o','u']
print("old list =",vowels)
vowels.insert(1,'e')
print("new list =",vowels)
INSERT( ) METHODS - PROGRAMS
Output
old list = ['a', 'i', 'o', 'u']
new list = ['a', 'e', 'i', 'o', 'u']
17
Example 2: Inserting a Tuple (as an Element) to the List
list = [{1, 2}, [5, 6, 7]]
print('old List: ', list)
number_tuple = (3, 4)
list.insert(1, number_tuple)
print('Updated List: ', list)
INSERT( ) METHODS - PROGRAMS
Output
old List: [{1, 2}, [5, 6, 7]]
Updated List: [{1, 2}, (3, 4), [5, 6, 7]]
18
 The pop() method takes a single argument (index) and
removes the element present at that index from the
list.
 If the index passed to the pop() method is not in the
range, it throws IndexError: pop index out of
range exception.
 The parameter passed to the pop() method is optional.
If no parameter is passed, the default index -1 is
passed as an argument.
 Also, the pop() method removes and returns the
element at the given index and updates the list.
 Syntax
POP( ) METHODS
list.pop(index) 19
Example 1: Pop Element at the Given Index from the List
list = ['Python', 'Java', 'C++', 'French', 'C‘]
return_value = language.pop(3)
print('Return Value: ', return_value)
print('Updated List: ', language)
POP( ) METHODS - PROGRAMS
Output
old list = ['Python', 'Java', 'C++', 'French', 'C']
Return Value: French
Updated List: ['Python', 'Java', 'C++', 'C']
20
Example 2: pop() when index is not passed
language = ['Python', 'Java', 'C++‘, 'C']
print('Return Value: ', language.pop())
print('Updated List: ', language)
print('Return Value: ', language.pop(-1))
print('Updated List: ', language)
POP( ) METHODS - PROGRAMS
Output
Return Value: C
Updated List: ['Python', 'Java', 'C++']
Return Value: C++ Updated List:
['Python', 'Java']
21
 The copy() method returns a shallow copy of the list.
 A list can be copied with = operator.
old_list = [1, 2, 3]
new_list = old_list
 The problem with copying the list in this way is that if
you modify the new_list, the old_list is also modified.
 Syntax
COPY( ) / ALIASING METHODS
new_list = old_list 22
Example 1: Copying a List
old_list = [1, 2, 3]
new_list = old_list
new_list.append('a')
print('New List:', new_list )
print('Old List:', old_list )
COPY( ) / ALIASING METHODS - PROGRAMS
Output
New List: [1, 2, 3, 'a']
Old List: [1, 2, 3, 'a']
23
 We need the original list unchanged when the new list
is modified, you can use copy() method.
 This is called shallow copy.
 The copy() method doesn't take any parameters.
 The copy() function returns a list. It doesn't modify the
original list.
 Syntax
SHALLOW COPY( ) / CLONING METHODS
new_list = list.copy()
24
Example 2: Shallow Copy of a List Using Slicing
list = [1,2,4]
new_list = list[:]
new_list.append(5)
print('Old List: ', list)
print('New List: ', new_list)
SHALLOW COPY( ) / CLONING METHODS - PROGRAMS
Output
Old List: [1, 2, 4]
New List: [1, 2, 4, 5]
25
 The remove() method searches for the given element
in the list and removes the first matching element.
 The remove() method takes a single element as an
argument and removes it from the list.
 If the element(argument) passed to the remove()
method doesn't exist, valueError exception is thrown.
 Syntax
list.remove(element)
REMOVE( ) METHODS
26
Example 1 :Remove Element From The List
list = [5,78,12,26,50]
print('Original list: ', list)
list.remove(12)
print('Updated list elements: ', list)
REMOVE( ) METHODS - PROGRAMS
Output
Original list: [5, 78, 12, 26,
50]Updated list: [5, 78, 26, 50]
27
 The reverse() method reverses the elements of a
given list.
 The reverse() function doesn't return any value. It
only reverses the elements and updates the list.
 Syntax
REVERSE( ) METHODS
list.reverse()
28
REVERSE( ) METHODS - PROGRAM
Example 1 :Reverse a List Using Slicing Operator
list = [1,5,8,6,11,55]
print('Original List:', list)
reversed_list = list[::-1]
print(‘Reversed List:', reversed_list)
Example 2: Reverse a List
list = [1,5,8,6,11,55]
print('Original List:', list)
list.reverse()
print('Reversed List:', list)
Output
Original List: [1, 5, 8, 6, 11, 55]
Reversed List: [55, 11, 6, 8, 5, 1]
Output
Original List: [1, 5, 8, 6, 11, 55]
Reversed List: [55, 11, 6, 8, 5, 1]
29
 The sort() method sorts the elements of a given list.
 The sort() method sorts the elements of a given list
in a specific order - Ascending or Descending.
 Syntax
SORT( ) METHODS
list.sort()
30
REVERSE( ) METHODS - PROGRAM
Example 1 :Sort a given List in ascending order
list = [1,15,88,6,51,55]
print('Original List:', list)
list.sort()
print('sorted List:', list)
Example 2 : Sort the list in Descending order
list = [1,15,88,6,51,55]
print('Original List:', list)
list.sort(reverse=True)
print('sorted List:', list)
Output
Original List: [1, 15, 88, 6, 51, 55]
sorted List: [1, 6, 15, 51, 55, 88]
Output
Original List: [1, 15, 88, 6, 51, 55]
sorted List: [88, 55, 51, 15, 6, 1] 31
PYTHON DICTIONARY
 Python dictionary is an unordered collection of items.
While other compound data types have only value as
an element, a dictionary has a key: value pair.
Creating a dictionary
 Creating a dictionary is as simple as placing items
inside curly braces {} separated by comma.
 An item has a key and the corresponding value
expressed as a pair, key: value.
 While values can be of any data type and can repeat,
keys must be of immutable type (string, number or tuple
with immutable elements) and must be unique.
32
ACCESS ELEMENTS FROM A DICTIONARY
 While indexing is used with other container types to access
values, dictionary uses keys. Key can be used either inside
square brackets or with the get() method.
d = {'name':'Ram', 'age': 26}
print("name is :",d['name'])
d['age']=33
d['Initial']='S‘
print("Updated dict :",d)
del d['Initial']
print("Updated dict :",d)
Output
name is : Ram
Updated dict : {'name': 'Ram', 'age': 33, 'Initial': 'S'}
Updated dict : {'name': 'Ram', 'age': 33}
33

More Related Content

What's hot

Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
2D Array
2D Array 2D Array
2D Array
Ehatsham Riaz
 
Circular queue
Circular queueCircular queue
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
TMARAGATHAM
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
PyData
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
nitamhaske
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
Mohammed Sikander
 
Python set
Python setPython set
Python set
Mohammed Sikander
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
Python Modules
Python ModulesPython Modules
Python Modules
Nitin Reddy Katkam
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
hydpy
 
Stacks
StacksStacks
Stacks
sweta dargad
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
Damian T. Gordon
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsAakash deep Singhal
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
Megha V
 

What's hot (20)

Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
 
2D Array
2D Array 2D Array
2D Array
 
Circular queue
Circular queueCircular queue
Circular queue
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)Introduction to NumPy (PyData SV 2013)
Introduction to NumPy (PyData SV 2013)
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
Python dictionary
Python   dictionaryPython   dictionary
Python dictionary
 
Python set
Python setPython set
Python set
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Stacks
StacksStacks
Stacks
 
Python: Modules and Packages
Python: Modules and PackagesPython: Modules and Packages
Python: Modules and Packages
 
Lecture 1 data structures and algorithms
Lecture 1 data structures and algorithmsLecture 1 data structures and algorithms
Lecture 1 data structures and algorithms
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 
Inline function
Inline functionInline function
Inline function
 
File handling in Python
File handling in PythonFile handling in Python
File handling in Python
 

Similar to Unit 4 python -list methods

Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
deepalishinkar1
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Python list
Python listPython list
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
Prof. Dr. K. Adisesha
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
Sakith1
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
Asst.prof M.Gokilavani
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
AshaWankar1
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
MCCMOTOR
 
List in Python
List in PythonList in Python
List in Python
Sharath Ankrajegowda
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
ToniyaP1
 
Python lists & sets
Python lists & setsPython lists & sets
Python lists & sets
Aswini Dharmaraj
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
NehaSpillai1
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
Koteswari Kasireddy
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
AnitaDevi158873
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
manohar25689
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
ChandanVatsa2
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
NeyXmarXd
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
Mahmoud Samir Fayed
 

Similar to Unit 4 python -list methods (20)

Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
Python list
Python listPython list
Python list
 
Python data handling notes
Python data handling notesPython data handling notes
Python data handling notes
 
Unit - 4.ppt
Unit - 4.pptUnit - 4.ppt
Unit - 4.ppt
 
Lecture2.pptx
Lecture2.pptxLecture2.pptx
Lecture2.pptx
 
GE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_NotesGE3151_PSPP_UNIT_4_Notes
GE3151_PSPP_UNIT_4_Notes
 
python_avw - Unit-03.pdf
python_avw - Unit-03.pdfpython_avw - Unit-03.pdf
python_avw - Unit-03.pdf
 
Python Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdfPython Unit 5 Questions n Notes.pdf
Python Unit 5 Questions n Notes.pdf
 
List in Python
List in PythonList in Python
List in Python
 
Data structures: linear lists
Data structures: linear listsData structures: linear lists
Data structures: linear lists
 
Python lists & sets
Python lists & setsPython lists & sets
Python lists & sets
 
Python Data Types.pdf
Python Data Types.pdfPython Data Types.pdf
Python Data Types.pdf
 
Python Data Types (1).pdf
Python Data Types (1).pdfPython Data Types (1).pdf
Python Data Types (1).pdf
 
updated_list.pptx
updated_list.pptxupdated_list.pptx
updated_list.pptx
 
Python-List.pptx
Python-List.pptxPython-List.pptx
Python-List.pptx
 
List Data Structure.docx
List Data Structure.docxList Data Structure.docx
List Data Structure.docx
 
List_tuple_dictionary.pptx
List_tuple_dictionary.pptxList_tuple_dictionary.pptx
List_tuple_dictionary.pptx
 
Python PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptxPython PRACTICAL NO 6 for your Assignment.pptx
Python PRACTICAL NO 6 for your Assignment.pptx
 
The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184The Ring programming language version 1.5.3 book - Part 22 of 184
The Ring programming language version 1.5.3 book - Part 22 of 184
 

Recently uploaded

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
Kamal Acharya
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
Amil Baba Dawood bangali
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
Kerry Sado
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
AafreenAbuthahir2
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
JoytuBarua2
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
Pipe Restoration Solutions
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
Massimo Talia
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
bakpo1
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
TeeVichai
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
Jayaprasanna4
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
FluxPrime1
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
ongomchris
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
zwunae
 

Recently uploaded (20)

Final project report on grocery store management system..pdf
Final project report on grocery store management system..pdfFinal project report on grocery store management system..pdf
Final project report on grocery store management system..pdf
 
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
NO1 Uk best vashikaran specialist in delhi vashikaran baba near me online vas...
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 
Hierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power SystemHierarchical Digital Twin of a Naval Power System
Hierarchical Digital Twin of a Naval Power System
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234WATER CRISIS and its solutions-pptx 1234
WATER CRISIS and its solutions-pptx 1234
 
Planning Of Procurement o different goods and services
Planning Of Procurement o different goods and servicesPlanning Of Procurement o different goods and services
Planning Of Procurement o different goods and services
 
The Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdfThe Benefits and Techniques of Trenchless Pipe Repair.pdf
The Benefits and Techniques of Trenchless Pipe Repair.pdf
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024Nuclear Power Economics and Structuring 2024
Nuclear Power Economics and Structuring 2024
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
一比一原版(SFU毕业证)西蒙菲莎大学毕业证成绩单如何办理
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Railway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdfRailway Signalling Principles Edition 3.pdf
Railway Signalling Principles Edition 3.pdf
 
ethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.pptethical hacking in wireless-hacking1.ppt
ethical hacking in wireless-hacking1.ppt
 
DESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docxDESIGN A COTTON SEED SEPARATION MACHINE.docx
DESIGN A COTTON SEED SEPARATION MACHINE.docx
 
space technology lecture notes on satellite
space technology lecture notes on satellitespace technology lecture notes on satellite
space technology lecture notes on satellite
 
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
一比一原版(IIT毕业证)伊利诺伊理工大学毕业证成绩单专业办理
 

Unit 4 python -list methods

  • 1. LIST METHODS Prepared by V.Kumararaja, AP/IT S.Thanga Prasad, AP/CSE Er.Perumal Manimekalai College of Engineering, Hosur 1
  • 2. LIST CREATION A list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types (integer, float, string etc.). Example: list = [1, 2, 3] # list with same data-types list = [1, "Hello", 3.4] # list with mixed data-types 2
  • 3. ACCESS ITEMS FROM A LIST  It can be access in several ways  Use the index operator [] to access an item in a list. Index starts from 0. So, a list having 5 elements will have index from 0 to 4.  Example: list = ['p','r','o','b','e'] print(list[2]) #Positive Indexing print(list[-2]) #Negative Indexing Output O b 3
  • 4. SLICE LISTS  Accessing a range of items in a list by using the slicing operator [ ] using (colon :).  Slicing can be best visualized by considering the index to be between the elements.  Example: list = ['p','r','o','b','e'] print(list[0:4]) #Positive print(list[-2:-1]) # Negative Output ['p', 'r', 'o', 'b'] ['b'] 4
  • 5. LIST METHODS  append() - Add an element to the end of the list.  count() - Returns the count of number of items passed as an argument.  extend() - Add all elements of a list to the another list.  index() - Returns the index of the first matched item.  insert() - Insert an item at the defined index.  pop() - Removes and returns an element at the given index.  copy() - Returns a shallow copy of the list  remove() - Removes an item from the list.  reverse() - Reverse the order of items in the list.  sort() - Sort items in a list in ascending order. 5
  • 6. APPEND() METHODS The append() method adds a single item to the existing list. The append() method only modifies the original list. It doesn't return any value. The append() method takes a single item and adds it to the end of the list. The item can be numbers, strings, another list, dictionary etc. Syntax list.append(item) 6
  • 7. Example 1: Adding Element to a List list = ['hi', 'hello'] print('old list: ', list) list.append('welcome!') print('Updated list: ', list) Example 2: Adding List to a List list = ['hi', 'hello'] print('old list: ', list) list1=['welcome‘] list.append(list1) print('Updated list: ', list) APPEND() METHODS - PROGRAMS Output old list: ['hi', 'hello'] Updated list: ['hi', 'hello‘,'welcome!'] Output old list: ['hi', 'hello'] Updated list: ['hi', 'hello', ['welcome']] 7
  • 8. COUNT() METHODS  Count() method counts how many times an element has occurred in a list and returns it.  The count() method takes a single argument:  element - element whose count is to be found.  The count() method returns the number of occurrences of an element in a list.  Syntax list.count(element) 8
  • 9. Example: Count the occurrence of an element in the list list = ['h','i','h','o','w','y','o','u','!','!'] print('The count of i is:',list.count('i')) print('The count of o is:',list.count('o')) Example 2: Count the occurrence of tuple and list inside the list list = ['a', ('h', 'i'), ('a', 'b'), [8, 4]] count = list.count(('a', 'b')) print("The count of ('a', 'b') is:", count) count = list.count([3, 4]) print("The count of [3, 4] is:", count) COUNT() METHODS - PROGRAMS Output The count of i is: 1 The count of o is: 2 Output The count of ('a', 'b') is: 1 The count of [3, 4] is: 0 9
  • 10.  The extend() extends the list by adding all items of a list to the end.  Extend() method takes a single argument (a list) and adds it to the end.  This method also add elements of other native data_types ,like tuple and set to the list,  Syntax EXTEND() METHODS list1.extend(list2) Note : The elements of list2 are added to the end of list1. list.extend(list(tuple_type)) Note : The elements of tuple are added to the end of list1. 10
  • 11. EXTEND() METHODS - PROGRAMS Example 1: Using extend() Method language = ['C', 'C++', 'Python'] language1 = ['JAVA', 'COBOL'] language.extend(language1) print('Language List: ', language) Output Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL'] 11
  • 12. Example 2: Add Elements of Tuple and Set to List language = ['C', 'C++', 'Python'] language_tuple = ['JAVA', 'COBOL'] language_set = {'.Net', 'C##'} language.extend(language_tuple) print('New Language List: ', language) language.extend(language_set) print('Newest Language List: ', language) EXTEND() METHODS - PROGRAMS Output New Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL'] Newest Language List: ['C', 'C++', 'Python', 'JAVA', 'COBOL', '.Net', 'C##'] 12
  • 13. INDEX( ) METHODS  Index() method search and find given element in the list and returns its position.  However, if the same element is present more than once, index() method returns its smallest/first position.  Index in Python starts from 0 not 1.  The index() method returns the index of the element in the list.  The index method takes a single argument:  element - element that is to be searched.  Syntax list.index(element) 13
  • 14. INDEX( ) METHODS - PROGRAMS Example 1: Find position of element present in the list and not present in the list list = ['h','i','h','o','w','y','o','u','!','!'] print('The count of i is:',list.index('i')) print('The count of o is:',list.index('o')) print('The count of o is:',list.index('z')) Output The count of i is: 1 The count of o is: 3 ValueError: 'z' is not in list 14
  • 15. Example 2: Find index of tuple and list inside a list random = ['a', ('a', 'd'),('a','b'), [3, 4]] index = random.index(('a', 'b')) print("The index of ('a', 'b'):", index) index = random.index([3, 4]) print("The index of [3, 4]:", index) INDEX( ) METHODS - PROGRAMS Output The index of ('a', 'b'): 2 The index of [3, 4]: 3 15
  • 16.  The insert() method inserts the element to the list at the given index.  The insert() function takes two parameters:  index - position where element needs to be inserted  element - this is the element to be inserted in the list  The insert() method only inserts the element to the list. It doesn't return any value.  Syntax INSERT( ) METHODS list.insert(index, element) 16
  • 17. Example 1: Inserting Element to List vowels=['a','i','o','u'] print("old list =",vowels) vowels.insert(1,'e') print("new list =",vowels) INSERT( ) METHODS - PROGRAMS Output old list = ['a', 'i', 'o', 'u'] new list = ['a', 'e', 'i', 'o', 'u'] 17
  • 18. Example 2: Inserting a Tuple (as an Element) to the List list = [{1, 2}, [5, 6, 7]] print('old List: ', list) number_tuple = (3, 4) list.insert(1, number_tuple) print('Updated List: ', list) INSERT( ) METHODS - PROGRAMS Output old List: [{1, 2}, [5, 6, 7]] Updated List: [{1, 2}, (3, 4), [5, 6, 7]] 18
  • 19.  The pop() method takes a single argument (index) and removes the element present at that index from the list.  If the index passed to the pop() method is not in the range, it throws IndexError: pop index out of range exception.  The parameter passed to the pop() method is optional. If no parameter is passed, the default index -1 is passed as an argument.  Also, the pop() method removes and returns the element at the given index and updates the list.  Syntax POP( ) METHODS list.pop(index) 19
  • 20. Example 1: Pop Element at the Given Index from the List list = ['Python', 'Java', 'C++', 'French', 'C‘] return_value = language.pop(3) print('Return Value: ', return_value) print('Updated List: ', language) POP( ) METHODS - PROGRAMS Output old list = ['Python', 'Java', 'C++', 'French', 'C'] Return Value: French Updated List: ['Python', 'Java', 'C++', 'C'] 20
  • 21. Example 2: pop() when index is not passed language = ['Python', 'Java', 'C++‘, 'C'] print('Return Value: ', language.pop()) print('Updated List: ', language) print('Return Value: ', language.pop(-1)) print('Updated List: ', language) POP( ) METHODS - PROGRAMS Output Return Value: C Updated List: ['Python', 'Java', 'C++'] Return Value: C++ Updated List: ['Python', 'Java'] 21
  • 22.  The copy() method returns a shallow copy of the list.  A list can be copied with = operator. old_list = [1, 2, 3] new_list = old_list  The problem with copying the list in this way is that if you modify the new_list, the old_list is also modified.  Syntax COPY( ) / ALIASING METHODS new_list = old_list 22
  • 23. Example 1: Copying a List old_list = [1, 2, 3] new_list = old_list new_list.append('a') print('New List:', new_list ) print('Old List:', old_list ) COPY( ) / ALIASING METHODS - PROGRAMS Output New List: [1, 2, 3, 'a'] Old List: [1, 2, 3, 'a'] 23
  • 24.  We need the original list unchanged when the new list is modified, you can use copy() method.  This is called shallow copy.  The copy() method doesn't take any parameters.  The copy() function returns a list. It doesn't modify the original list.  Syntax SHALLOW COPY( ) / CLONING METHODS new_list = list.copy() 24
  • 25. Example 2: Shallow Copy of a List Using Slicing list = [1,2,4] new_list = list[:] new_list.append(5) print('Old List: ', list) print('New List: ', new_list) SHALLOW COPY( ) / CLONING METHODS - PROGRAMS Output Old List: [1, 2, 4] New List: [1, 2, 4, 5] 25
  • 26.  The remove() method searches for the given element in the list and removes the first matching element.  The remove() method takes a single element as an argument and removes it from the list.  If the element(argument) passed to the remove() method doesn't exist, valueError exception is thrown.  Syntax list.remove(element) REMOVE( ) METHODS 26
  • 27. Example 1 :Remove Element From The List list = [5,78,12,26,50] print('Original list: ', list) list.remove(12) print('Updated list elements: ', list) REMOVE( ) METHODS - PROGRAMS Output Original list: [5, 78, 12, 26, 50]Updated list: [5, 78, 26, 50] 27
  • 28.  The reverse() method reverses the elements of a given list.  The reverse() function doesn't return any value. It only reverses the elements and updates the list.  Syntax REVERSE( ) METHODS list.reverse() 28
  • 29. REVERSE( ) METHODS - PROGRAM Example 1 :Reverse a List Using Slicing Operator list = [1,5,8,6,11,55] print('Original List:', list) reversed_list = list[::-1] print(‘Reversed List:', reversed_list) Example 2: Reverse a List list = [1,5,8,6,11,55] print('Original List:', list) list.reverse() print('Reversed List:', list) Output Original List: [1, 5, 8, 6, 11, 55] Reversed List: [55, 11, 6, 8, 5, 1] Output Original List: [1, 5, 8, 6, 11, 55] Reversed List: [55, 11, 6, 8, 5, 1] 29
  • 30.  The sort() method sorts the elements of a given list.  The sort() method sorts the elements of a given list in a specific order - Ascending or Descending.  Syntax SORT( ) METHODS list.sort() 30
  • 31. REVERSE( ) METHODS - PROGRAM Example 1 :Sort a given List in ascending order list = [1,15,88,6,51,55] print('Original List:', list) list.sort() print('sorted List:', list) Example 2 : Sort the list in Descending order list = [1,15,88,6,51,55] print('Original List:', list) list.sort(reverse=True) print('sorted List:', list) Output Original List: [1, 15, 88, 6, 51, 55] sorted List: [1, 6, 15, 51, 55, 88] Output Original List: [1, 15, 88, 6, 51, 55] sorted List: [88, 55, 51, 15, 6, 1] 31
  • 32. PYTHON DICTIONARY  Python dictionary is an unordered collection of items. While other compound data types have only value as an element, a dictionary has a key: value pair. Creating a dictionary  Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.  An item has a key and the corresponding value expressed as a pair, key: value.  While values can be of any data type and can repeat, keys must be of immutable type (string, number or tuple with immutable elements) and must be unique. 32
  • 33. ACCESS ELEMENTS FROM A DICTIONARY  While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method. d = {'name':'Ram', 'age': 26} print("name is :",d['name']) d['age']=33 d['Initial']='S‘ print("Updated dict :",d) del d['Initial'] print("Updated dict :",d) Output name is : Ram Updated dict : {'name': 'Ram', 'age': 33, 'Initial': 'S'} Updated dict : {'name': 'Ram', 'age': 33} 33