Python List Methods
Python List Methods with Examples
1. append(item) - Adds an item to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4) # my_list becomes [1, 2, 3, 4]
2. extend(iterable) - Extends the list by appending elements from an iterable.
Example:
my_list = [1, 2]
my_list.extend([3, 4]) # my_list becomes [1, 2, 3, 4]
3. insert(index, item) - Inserts an item at a specified index.
Example:
my_list = [1, 3]
my_list.insert(1, 2) # my_list becomes [1, 2, 3]
4. remove(item) - Removes the first occurrence of the specified item.
Example:
my_list = [1, 2, 3]
my_list.remove(2) # my_list becomes [1, 3]
5. pop(index) - Removes and returns an item at the specified index. Default is the last item.
Example:
my_list = [1, 2, 3]
my_list.pop() # Returns 3, my_list becomes [1, 2]
6. index(item) - Returns the index of the first occurrence of the item.
Example:
my_list = [1, 2, 3]
my_list.index(2) # Returns 1
7. count(item) - Returns the count of the item in the list.
Example:
my_list = [1, 2, 2, 3]
my_list.count(2) # Returns 2
8. reverse() - Reverses the list in place.
Example:
my_list = [1, 2, 3]
my_list.reverse() # my_list becomes [3, 2, 1]
9. sort() - Sorts the list in ascending order.
Example:
my_list = [3, 1, 2]
my_list.sort() # my_list becomes [1, 2, 3]
10. clear() - Removes all items from the list.
Example:
my_list = [1, 2, 3]
my_list.clear() # my_list becomes []
Python Tuple and Methods
Python Tuple and Its Methods
1. Tuples are immutable sequences in Python.
Example:
my_tuple = (1, 2, 3)
Tuple Methods:
1. count(item) - Returns the count of the item in the tuple.
Example:
my_tuple = (1, 2, 2, 3)
my_tuple.count(2) # Returns 2
2. index(item) - Returns the index of the first occurrence of the item.
Example:
my_tuple = (1, 2, 3)
my_tuple.index(2) # Returns 1
Python Functions and Methods
Python Functions and Methods
1. A function is a reusable block of code that performs a specific task.
Example:
def greet(name):
return f"Hello, {name}"
2. Built-in function examples:
- len(): Returns the length of an object.
- type(): Returns the type of an object.
Custom Functions:
Example:
def add(a, b):
return a + b
Function Methods:
Functions do not have specific methods like lists or tuples, but they can be treated as objects.
Python List Methods
Python List Methods with Examples
1. append(item) - Adds an item to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.append(4) # my_list becomes [1, 2, 3, 4]
2. extend(iterable) - Extends the list by appending elements from an iterable.
Example:
my_list = [1, 2]
my_list.extend([3, 4]) # my_list becomes [1, 2, 3, 4]
3. insert(index, item) - Inserts an item at a specified index.
Example:
my_list = [1, 3]
my_list.insert(1, 2) # my_list becomes [1, 2, 3]
4. remove(item) - Removes the first occurrence of the specified item.
Example:
my_list = [1, 2, 3]
my_list.remove(2) # my_list becomes [1, 3]
5. pop(index) - Removes and returns an item at the specified index. Default is the last item.
Example: