Learning Python? Mastering methods is a must. Python methods help you manipulate data, optimize code, and write cleaner programs. Here are 16 practical Python methods every beginner should know, with definitions, examples, and official documentation links.
1. str.lower()
– Convert a String to Lowercase
Definition: Converts all uppercase characters in a string to lowercase.
text = "HELLO WORLD"
print(text.lower())
Output:
hello world
Explanation:
- Helps normalize text for case-insensitive comparisons.
- Useful in user input processing.
- Official doc: str.lower()
2. str.upper()
– Convert a String to Uppercase
Definition: Converts all lowercase characters in a string to uppercase.
text = "hello world"
print(text.upper())
Output:
HELLO WORLD
Explanation:
- Useful for formatting text consistently.
- Helps with case-insensitive checks.
- Official doc: str.upper()
3. str.strip()
– Remove Whitespace from Both Ends
Definition: Removes leading and trailing whitespace from a string.
text = " Hello, Python! "
print(text.strip())
Output:
Hello, Python!
Explanation:
- Helps clean user input.
- Removes accidental spaces in formatted strings.
- Official doc: str.strip()
4. str.replace()
– Replace Substrings
Definition: Replaces occurrences of a substring within a string.
text = "Hello, world!"
print(text.replace("world", "Python"))
Output:
Hello, Python!
Explanation:
- Helps modify text dynamically.
- Useful in search-and-replace operations.
- Official doc: str.replace()
5. str.split()
– Split a String into a List
Definition: Splits a string into a list based on a delimiter.
text = "apple,banana,cherry"
print(text.split(","))
Output:
['apple', 'banana', 'cherry']
Explanation:
- Converts CSV-like strings into lists.
- Useful for parsing data.
- Official doc: str.split()
6. list.append()
– Add an Item to a List
Definition: Adds a new item to the end of a list.
fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)
Output:
['apple', 'banana', 'cherry']
Explanation:
- Adds elements dynamically to lists.
- Useful in loops and data collection.
- Official doc: list.append()
7. list.remove()
– Remove an Item from a List
Definition: Removes the first occurrence of a specified item from a list.
fruits = ["apple", "banana", "cherry"]
fruits.remove("banana")
print(fruits)
Output:
['apple', 'cherry']
Explanation:
- Removes specific items by value.
- Raises an error if the item is not in the list.
- Official doc: list.remove()
8. sorted()
– Sort a List
Definition: Returns a new sorted list from an iterable.
numbers = [3, 1, 4, 1, 5, 9]
print(sorted(numbers))
Output:
[1, 1, 3, 4, 5, 9]
Explanation:
- Returns a new sorted list without modifying the original.
- Works with different data types.
- Official doc: sorted()
9. dict.keys()
– Get Keys from a Dictionary
Definition: Returns a view object with dictionary keys.
data = {"name": "Alice", "age": 25}
print(list(data.keys()))
Output:
['name', 'age']
Explanation:
- Helps iterate over dictionary keys.
- Useful for checking the existence of keys.
- Official doc: dict.keys()
10. set.add()
– Add an Item to a Set
Definition: Adds an item to a set.
numbers = {1, 2, 3}
numbers.add(4)
print(numbers)
Output:
{1, 2, 3, 4}
Explanation:
- Ensures unique values.
- Helps in membership testing.
- Official doc: set.add()
11. set.remove()
– Remove an Item from a Set
Definition: Removes an item from a set. Raises an error if the item is not found.
numbers = {1, 2, 3}
numbers.remove(2)
print(numbers)
Output:
{1, 3}
Explanation:
- Removes elements safely.
- Use
discard()
to avoid errors if the item doesn't exist. - Official doc: set.remove()
12. enumerate()
– Number Items in an Iterable
Definition: Returns an enumerate object containing index-value pairs.
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 apple
1 banana
2 cherry
Explanation:
- Useful in loops where index tracking is needed.
- Official doc: enumerate()
13. map()
– Apply a Function to an Iterable
Definition: Applies a function to all elements in an iterable.
numbers = [1, 2, 3]
squared = list(map(lambda x: x**2, numbers))
print(squared)
Output:
[1, 4, 9]
Explanation:
- Ideal for functional programming.
- Official doc: map()
14. filter()
– Filter Elements in an Iterable
Definition: Filters elements that meet a condition.
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)
Output:
[2, 4]
Explanation:
- Keeps only elements that pass a condition.
- Official doc: filter()
15. zip()
– Combine Iterables Element-wise
Definition: Combines multiple iterables into tuples of corresponding elements.
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
combined = list(zip(names, ages))
print(combined)
Output:
[("Alice", 25), ("Bob", 30), ("Charlie", 35)]
Explanation:
- Pairs elements from multiple iterables.
- Official doc: zip()
16. any()
– Check if Any Element is True
Definition: Returns True
if at least one element in an iterable is truthy.
values = [0, 0, 1, 0]
print(any(values))
Output:
True
Explanation:
- Useful for checking conditions.
- Official doc: any()
Mastering these Python methods will level up your coding game. Keep practicing, and don't forget to check out Python's official documentation for more details!
📖 Official Python Docs: Python 3 Library Reference
Top comments (0)