Lists
1. clear()
The clear()
method removes all items from the list, leaving it empty.
Example:
my_list = [1, 2, 3, 4, 5]
my_list.clear()
print(my_list) # Output: []
2. copy()
The copy()
method returns a shallow copy of the list. Modifications to the copied list do not affect the original list.
Example:
original_list = [1, 2, 3]
copied_list = original_list.copy()
copied_list.append(4)
print(original_list) # Output: [1, 2, 3]
print(copied_list) # Output: [1, 2, 3, 4]
3. count(item)
The count()
method returns the number of occurrences of the specified item
in the list.
Example:
my_list = [1, 2, 2, 3, 2, 4]
count = my_list.count(2)
print(count) # Output: 3
4. extend(iterable)
The extend()
method appends the elements of an iterable (e.g., a list or tuple) to the end of the list.
Example:
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
5. index(item[, start[, end]])
The index()
method returns the index of the first occurrence of the specified item
in the list. You can specify optional start
and end
parameters to search within a specific slice of the list.
Example:
my_list = [10, 20, 30, 20, 40]
index = my_list.index(20)
print(index) # Output: 1
6. insert(index, item)
The insert()
method inserts the specified item
at the specified index
in the list.
Example:
my_list = [1, 2, 3]
my_list.insert(1, 4)
print(my_list) # Output: [1, 4, 2, 3]
7. pop([index])
The pop()
method removes and returns the element at the specified index
. If no index
is provided, it removes and returns the last element.
Example:
my_list = [1, 2, 3, 4, 5]
popped_item = my_list.pop(2)
print(popped_item) # Output: 3
print(my_list) # Output: [1, 2, 4, 5]
8. remove(item)
The remove()
method removes the first occurrence of the specified item
from the list.
Example:
my_list = [1, 2, 3, 2, 4]
my_list.remove(2)
print(my_list) # Output: [1, 3, 2, 4]
9. reverse()
The reverse()
method reverses the order of elements in the list in place.
Example:
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
10. sort(key=None, reverse=False)
The sort()
method sorts the elements of the list in ascending order by default. You can specify a custom sorting key
function and set reverse
to True
to sort in descending order.
Example:
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
my_list.sort()
print(my_list) # Output: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
# Sorting in descending order
my_list.sort(reverse=True)
print(my_list) # Output: [9, 6, 5, 5, 5, 4, 3, 3, 2, 1, 1]
These advanced list methods provide you with powerful tools for manipulating and working with lists in Python, allowing you to perform various operations such as clearing, copying, counting, extending, indexing, inserting, popping, removing, reversing, and sorting lists.
Tuples
1. count(item)
The count()
method returns the number of occurrences of the specified item
in the tuple.
Example:
my_tuple = (1, 2, 2, 3, 2, 4)
count = my_tuple.count(2)
print(count) # Output: 3
In this example, the count()
method is used to count how many times the value 2
appears in the tuple.
2. index(item[, start[, end]])
The index()
method returns the index of the first occurrence of the specified item
in the tuple. You can specify optional start
and end
parameters to search within a specific slice of the tuple.
Example:
my_tuple = (10, 20, 30, 20, 40)
index = my_tuple.index(20)
print(index) # Output: 1
In this example, the index()
method is used to find the index of the first occurrence of the value 20
in the tuple.
Tuple methods like count()
and index()
are handy for working with tuples when you need to find specific elements or count occurrences within an immutable sequence.
Dictionary
1. clear()
The clear()
method removes all items from the dictionary, making it empty.
Example:
my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}
my_dict.clear()
print(my_dict) # Output: {}
2. copy()
The copy()
method returns a shallow copy of the dictionary. Modifications to the copied dictionary do not affect the original dictionary.
Example:
original_dict = {'name': 'Alice', 'age': 30}
copied_dict = original_dict.copy()
copied_dict['age'] = 31
print(original_dict) # Output: {'name': 'Alice', 'age': 30}
print(copied_dict) # Output: {'name': 'Alice', 'age': 31}
3. fromkeys(keys, [value])
The fromkeys()
method creates a new dictionary with the specified keys
and an optional default value
for all keys.
Example:
keys = ['name', 'age', 'city']
default_value = 'unknown'
my_dict = dict.fromkeys(keys, default_value)
print(my_dict)
# Output: {'name': 'unknown', 'age': 'unknown', 'city': 'unknown'}
In this example, a new dictionary is created with keys from the keys
list, and all values are set to the default_value
.
4. get(key, [default])
:
The get()
method returns the value associated with the specified key
in the dictionary. If the key
is not found, it returns an optional default
value (default is None
).
Example:
my_dict = {'name': 'Alice', 'age': 30}
name = my_dict.get('name')
city = my_dict.get('city', 'unknown')
print(name) # Output: 'Alice'
print(city) # Output: 'unknown'
In this example, the get()
method retrieves the values associated with keys 'name' and 'city'. Since 'city' is not found in the dictionary, it returns the default value 'unknown'.
5. items()
:
The items()
method returns a view of all key-value pairs (items) in the dictionary as tuples.
Example:
my_dict = {'name': 'Alice', 'age': 30}
items = my_dict.items()
print(items) # Output: dict_items([('name', 'Alice'), ('age', 30)])
This method is useful for iterating through the key-value pairs in a dictionary.
6. keys()
:
The keys()
method returns a view of all keys in the dictionary.
Example:
my_dict = {'name': 'Alice', 'age': 30}
keys = my_dict.keys()
print(keys) # Output: dict_keys(['name', 'age'])
7. pop(key, [default])
:
The pop()
method removes the item with the specified key
from the dictionary and returns its value. If the key
is not found, it returns an optional default
value (default is an error).
Example:
my_dict = {'name': 'Alice', 'age': 30}
name = my_dict.pop('name')
city = my_dict.pop('city', 'unknown')
print(name) # Output: 'Alice'
print(city) # Output: 'unknown'
8. popitem()
The popitem()
method removes and returns an arbitrary (key, value) pair from the dictionary.
Example:
my_dict = {'name': 'Alice', 'age': 30}
item = my_dict.popitem()
print(item) # Output: ('age', 30)
9. setdefault(key, [default])
The setdefault()
method returns the value associated with the specified key
in the dictionary. If the key
is not found, it inserts the key
with an optional default
value (default is None
) and returns the default
value.
Example:
my_dict = {'name': 'Alice', 'age': 30}
city = my_dict.setdefault('city', 'New York')
print(city) # Output: 'New York'
10. update([other])
The update()
method updates the dictionary with key-value pairs from another dictionary or an iterable of key-value pairs.
Example:
my_dict = {'name': 'Alice', 'age': 30}
my_dict.update({'city': 'New York', 'gender': 'female'})
print(my_dict)
# Output: {'name': 'Alice', 'age': 30, 'city': 'New York', 'gender': 'female'}
11. values()
The values()
method returns a view of all values in the dictionary.
Example:
my_dict = {'name': 'Alice', 'age': 30}
values = my_dict.values()
print(values) # Output: dict_values(['Alice', 30])
These advanced dictionary methods provide you with powerful tools for manipulating and working with dictionaries in Python, allowing you to perform various operations such as clearing, copying, retrieving values, iterating through items, and more.
Sets
1. add(element)
The add()
method adds a single element
to the set. If the element is already present, it has no effect.
Example:
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.add(2) # No effect, 2 is already in the set
print(my_set) # Output: {1, 2, 3, 4}
2. clear()
The clear()
method removes all elements from the set, making it empty.
Example:
my_set = {1, 2, 3}
my_set.clear()
print(my_set) # Output: set()
3. copy()
The copy()
method returns a shallow copy of the set. Modifications to the copied set do not affect the original set.
Example:
original_set = {1, 2, 3}
copied_set = original_set.copy()
copied_set.add(4)
print(original_set) # Output: {1, 2, 3}
print(copied_set) # Output: {1, 2, 3, 4}
4. difference(*others)
The difference()
method returns a new set that contains elements that are in the original set but not in any of the other specified sets.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
difference_set = set1.difference(set2)
print(difference_set) # Output: {1, 2}
5. difference_update(*others)
The difference_update()
method removes from the original set elements that are present in one or more other specified sets.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.difference_update(set2)
print(set1) # Output: {1, 2}
6. discard(element)
The discard()
method removes the specified element
from the set if it exists. If the element is not present, it has no effect.
Example:
my_set = {1, 2, 3}
my_set.discard(2)
print(my_set) # Output: {1, 3}
my_set.discard(4) # No effect, 4 is not in the set
print(my_set) # Output: {1, 3}
7. intersection(*others)
The intersection()
method returns a new set that contains elements that are present in both the original set and all other specified sets.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
intersection_set = set1.intersection(set2)
print(intersection_set) # Output: {3, 4}
8. intersection_update(*others)
The intersection_update()
method updates the original set to contain only the elements that are present in both the original set and all other specified sets.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.intersection_update(set2)
print(set1) # Output: {3, 4}
9. isdisjoint(other)
The isdisjoint()
method returns True
if the original set has no elements in common with the specified other
set. Otherwise, it returns False
.
Example:
set1 = {1, 2, 3}
set2 = {4, 5, 6}
is_disjoint = set1.isdisjoint(set2)
print(is_disjoint) # Output: True
10. issubset(other)
The issubset()
method returns True
if the original set is a subset of the specified other
set. Otherwise, it returns False
.
Example:
set1 = {1, 2}
set2 = {1, 2, 3, 4}
is_subset = set1.issubset(set2)
print(is_subset) # Output: True
11. issuperset(other)
The issuperset()
method returns True
if the original set is a superset of the specified other
set. Otherwise, it returns False
.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4}
is_superset = set1.issuperset(set2)
print(is_superset) # Output: True
12. pop()
The pop()
method removes and returns an arbitrary element from the set. If the set is empty, it raises a KeyError
.
Example:
my_set = {1, 2, 3}
popped_element = my_set.pop()
print(popped_element) # Output: An arbitrary element (e.g., 1, 2, or 3)
13. remove(element)
The remove()
method removes the specified element
from the set. If the element is not present, it raises a KeyError
.
Example:
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Output: {1, 3}
# Attempting to remove a non-existent element
try:
my_set.remove(4)
except KeyError as e:
print("Element not found:", e)
# Output: Element not found: 4
14. symmetric_difference(other)
The symmetric_difference()
method returns a new set that contains elements that are in either the original set or the specified other
set, but not in both.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
symmetric_diff_set = set1.symmetric_difference(set2)
print(symmetric_diff_set) # Output: {1, 2, 5, 6}
15. symmetric_difference_update(other)
The symmetric_difference_update()
method updates the original set to contain elements that are in either the original set or the specified other
set, but not in both.
Example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.symmetric_difference_update(set2)
print(set1) # Output: {1, 2, 5, 6}
16. union(*others)
The union()
method returns a new set that contains all elements that are in the original set or any of the other specified sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = set1.union(set2)
print(union_set) # Output: {1, 2, 3, 4, 5}
17. update(*others)
The update()
method updates the original set to include all elements that are in the original set or any of the other specified sets.
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
print(set1) # Output: {1, 2, 3, 4, 5}
These advanced set methods provide powerful tools for working with sets in Python, allowing you to add elements, clear the set, create copies, find differences, update differences, remove elements, and find intersections efficiently.