This README provides a quick reference for frequently used Python operations, such as accessing elements, string manipulations, sorting, searching, and more.
- Accessing Elements
- String Manipulation
- Sorting Lists
- Searching in Collections
- Mathematical Operations
- Data Structures
- File Handling
- Error Handling
- Miscellaneous
my_list = [10, 20, 30, 40, 50]
last_element = my_list[-1] # Output: 50
first_element = my_list[0] # Output: 10
subset = my_list[1:4] # Output: [20, 30, 40]
my_string = "Python"
reversed_string = my_string[::-1] # Output: "nohtyP"
uppercase_string = my_string.upper() # Output: "PYTHON"
lowercase_string = my_string.lower() # Output: "python"
if "Py" in my_string:
print("Substring found!") # Output: "Substring found!"
numbers = [5, 2, 9, 1, 5, 6]
sorted_numbers = sorted(numbers) # Output: [1, 2, 5, 5, 6, 9]
sorted_desc = sorted(numbers, reverse=True) # Output: [9, 6, 5, 5, 2, 1]
numbers.sort() # numbers is now [1, 2, 5, 5, 6, 9]
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Banana is in the list!") # Output: "Banana is in the list!"
index = fruits.index("banana") # Output: 1
max_value = max(numbers) # Output: 9
min_value = min(numbers) # Output: 1
total = sum(numbers) # Output: 28
num_range = list(range(1, 11)) # Output: [1, 2, 3, ..., 10]
person = {"name": "Alice", "age": 25, "city": "New York"}
name = person.get("name") # Output: "Alice"
person.pop("age") # Removes "age" key from dictionary
with open("example.txt", "r") as file:
content = file.read()
with open("example.txt", "w") as file:
file.write("Hello, Python!")
with open("example.txt", "a") as file:
file.write("
Adding more content.")
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
x = int("text")
except (ValueError, TypeError):
print("Invalid conversion!")
unique_numbers = list(set(numbers)) # Output: [1, 2, 5, 6, 9]
a, b = 5, 10
a, b = b, a # Now a = 10, b = 5
squares = [x ** 2 for x in range(1, 6)] # Output: [1, 4, 9, 16, 25]
These are some of the most commonly used Python operations. Whether you're working with lists, strings, dictionaries, or files, these quick references will help you write efficient Python code.
Happy coding!