0% found this document useful (0 votes)
23 views5 pages

Built-In Methods On List

Uploaded by

sarangpsivan
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)
23 views5 pages

Built-In Methods On List

Uploaded by

sarangpsivan
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/ 5

Built-in Methods on List in Python

In Python, lists are commonly used data structures.


Lists have several built-in methods that allow you to
modify perform operations on them.
Here's five important list methods:
append(), clear(),copy(), count(),sort()

1.append()
The append() method is used to add an item to the
end of the list. It modifies the original list.
Syntax:
list name .append(element)
Example:
my_list=[1,2,3]
my_list.append(4)
print(my_list)
Output:
[1, 2, 3, 4]
2. clear()

The clear() method removes all elements from the


list, making it an empty list.
Syntax:
list.clear()
Example:
my_list=[1,2,3,4]
my_list.clear()
print(my_list)
Output:
[] #list items has been removed

3. copy()

The copy() method creates a shallow copy of the list.


Changes made to the copied list will not affect the
original list.

Syntax:
new_list = list.copy()
Example:
my_list=[1,2,3]
new_list=my_list.copy()
new_list.append(4)
print('OriginalList:',my_list)
print('Copied List:', new_list)
Output:
OriginalList:[1,2,3]
Copied List: [1, 2, 3, 4]

4. count()

The count() method returns the number of


occurrences of a specified element in the list.
Syntax:
count = list.count(element)
Example:
my_list=[1,2,2,3,4,2]
count_of_twos=my_list.count(2)
print(count_of_twos)
Output:
3
5. sort()

The sort() method sorts the elements of the list in


ascending order by default. It modifies the original
list. also sorting can be specified by
(ascending/descending) order by ‘key’ for custom
sorting.
Syntax:
list.sort(reverse=False, key=None)
Example 1 (Ascending Order):
my_list = [3, 1, 4, 2]
my_list.sort()
print(my_list)
Output:
[1, 2, 3, 4]
Example 2 (Descending Order):
my_list = [3, 1, 4, 2]
my_list.sort(reverse=True)
print(my_list)
Output:
[4, 3, 2, 1]

You might also like