0% found this document useful (0 votes)
1 views2 pages

Python List Methods With Examples

Uploaded by

chennujaswanth7
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)
1 views2 pages

Python List Methods With Examples

Uploaded by

chennujaswanth7
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/ 2

Python List, Tuple & Set Methods with Examples

List Methods
append()
Adds an element to the end of the list.
my_list = [1, 2]
my_list.append(3)
print(my_list) # Output: [1, 2, 3]

extend()
Appends elements from another iterable (like list).
my_list = [1, 2]
my_list.extend([3, 4])
print(my_list) # Output: [1, 2, 3, 4]

insert()
Inserts an element at a specific index.
my_list = [1, 3]
my_list.insert(1, 2)
print(my_list) # Output: [1, 2, 3]

remove()
Removes the first occurrence of a value.
my_list = [1, 2, 3]
my_list.remove(2)
print(my_list) # Output: [1, 3]

pop()
Removes and returns the last item by default.
my_list = [1, 2, 3]
item = my_list.pop()
print(item) # Output: 3

clear()
Removes all items from the list.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []

index()
Returns the index of the first match of value.
my_list = [10, 20, 30]
print(my_list.index(20)) # Output: 1

count()
Returns the number of occurrences of a value.
my_list = [1, 2, 2, 3]
print(my_list.count(2)) # Output: 2
Python List, Tuple & Set Methods with Examples

sort()
Sorts the list in ascending order by default.
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]

reverse()
Reverses the elements of the list.
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]

copy()
Returns a shallow copy of the list.
my_list = [1, 2, 3]
copy_list = my_list.copy()
print(copy_list) # Output: [1, 2, 3]

You might also like