Python provides several useful methods for manipulating lists:
1) Methods like append(), extend(), insert() allow adding elements to lists in various ways.
2) sort() arranges list elements in ascending order.
3) pop() removes and returns the last/specific indexed element.
4) Other methods like count(), remove() allow filtering lists by checking/deleting elements.
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 ratings0% found this document useful (0 votes)
9 views2 pages
List Methods
Python provides several useful methods for manipulating lists:
1) Methods like append(), extend(), insert() allow adding elements to lists in various ways.
2) sort() arranges list elements in ascending order.
3) pop() removes and returns the last/specific indexed element.
4) Other methods like count(), remove() allow filtering lists by checking/deleting elements.
all of the elements. ['a', 'b', 'e', 'c', 'd'] Syntax: v) count() listname1.extend(listname2) - returns the number of occurrences of Example the given substring.
>>> t1 = ['a', 'b', 'c'] - Syntax:
>>> t2 = ['d', 'e'] listname.count(element) -
Example >>> t1.extend(t2) >>> t = ['d', 'c', 'a', 'e', 'b', 'a'] >>> t1 >>>t.count('a') ['a', 'b', 'c', 'd', 'e'] 2 This example leaves t2 unmodified. vi) insert() iii) sort() - used to insert the given element in the - arranges the elements of the list in given position. ascending order. -Syntax: Syntax: listname.insert(index,element) listname.sort() - Example:
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.insert(4,'f') - Example:
>>> t >>> t = ['d', 'c', 'e', 'b', 'a']
['d', 'c', 'e', 'b', 'f', 'a'] >>> t.pop(2)
vii) pop() 'e'
- removes and returns the last element in viii) remove()
the list. - If the element to be deleted is known - Syntax: and the removed value is not needed, remove() can be used to remove the given element. listname.pop() - Syntax: - Example: listname.remove(element) >>> t = ['d', 'c', 'e', 'b', 'a'] >>> t.pop() - Example: