SlideShare a Scribd company logo
1 of 33
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

Arrays in python
Arrays in pythonArrays in python
Arrays in pythonmoazamali28
 
Functions in python
Functions in pythonFunctions in python
Functions in pythoncolorsof
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statementnarmadhakin
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in pythonTMARAGATHAM
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonPriyankaC44
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D arraySangani Ankur
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Presentation on array
Presentation on array Presentation on array
Presentation on array topu93
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptxAkshayAggarwal79
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in PythonDevashish Kumar
 

What's hot (20)

Arrays in python
Arrays in pythonArrays in python
Arrays in python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python Modules
Python ModulesPython Modules
Python Modules
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
Python set
Python setPython set
Python set
 
stack & queue
stack & queuestack & queue
stack & queue
 
Modules and packages in python
Modules and packages in pythonModules and packages in python
Modules and packages in python
 
Strings in python
Strings in pythonStrings in python
Strings in python
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
 
concept of Array, 1D & 2D array
concept of Array, 1D & 2D arrayconcept of Array, 1D & 2D array
concept of Array, 1D & 2D array
 
Arrays in c
Arrays in cArrays in c
Arrays in c
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Presentation on array
Presentation on array Presentation on array
Presentation on array
 
Arrays
ArraysArrays
Arrays
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Python variables and data types.pptx
Python variables and data types.pptxPython variables and data types.pptx
Python variables and data types.pptx
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
 
Python tuple
Python   tuplePython   tuple
Python tuple
 

Similar to Unit 4 python -list methods

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
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
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
 

Recently uploaded

Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxpritamlangde
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementDr. Deepak Mudgal
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Servicemeghakumariji156
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxMuhammadAsimMuhammad6
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxNANDHAKUMARA10
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptAfnanAhmad53
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesMayuraD1
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxkalpana413121
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Call Girls Mumbai
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXssuser89054b
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdfKamal Acharya
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdfKamal Acharya
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxSCMS School of Architecture
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueBhangaleSonal
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...ronahami
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptxJIT KUMAR GUPTA
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdfAldoGarca30
 

Recently uploaded (20)

Digital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptxDigital Communication Essentials: DPCM, DM, and ADM .pptx
Digital Communication Essentials: DPCM, DM, and ADM .pptx
 
Ground Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth ReinforcementGround Improvement Technique: Earth Reinforcement
Ground Improvement Technique: Earth Reinforcement
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptxOrlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
Orlando’s Arnold Palmer Hospital Layout Strategy-1.pptx
 
Integrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - NeometrixIntegrated Test Rig For HTFE-25 - Neometrix
Integrated Test Rig For HTFE-25 - Neometrix
 
Electromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptxElectromagnetic relays used for power system .pptx
Electromagnetic relays used for power system .pptx
 
fitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .pptfitting shop and tools used in fitting shop .ppt
fitting shop and tools used in fitting shop .ppt
 
DeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakesDeepFakes presentation : brief idea of DeepFakes
DeepFakes presentation : brief idea of DeepFakes
 
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in South Ex (delhi) call me [🔝9953056974🔝] escort service 24X7
 
UNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptxUNIT 4 PTRP final Convergence in probability.pptx
UNIT 4 PTRP final Convergence in probability.pptx
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Online electricity billing project report..pdf
Online electricity billing project report..pdfOnline electricity billing project report..pdf
Online electricity billing project report..pdf
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...Max. shear stress theory-Maximum Shear Stress Theory ​  Maximum Distortional ...
Max. shear stress theory-Maximum Shear Stress Theory ​ Maximum Distortional ...
 
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
COST-EFFETIVE  and Energy Efficient BUILDINGS ptxCOST-EFFETIVE  and Energy Efficient BUILDINGS ptx
COST-EFFETIVE and Energy Efficient BUILDINGS ptx
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 

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