Python Medium Questions
1. How to reverse a string in Python?
-> reversed_str = 'hello'[::-1]
2. How to check if a number is prime?
-> def is_prime(n):
-> if n < 2:
-> return False
-> for i in range(2, int(n**0.5) + 1):
-> if n % i == 0:
-> return False
-> return True
3. How to find the largest number in a list?
-> largest = max([3, 7, 2, 8, 5])
4. How to remove duplicates from a list?
-> unique_items = list(set([1, 2, 2, 3, 4, 4, 5]))
5. How to read a file in Python?
-> with open('[Link]', 'r') as f:
-> content = [Link]()
6. How to write to a file in Python?
-> with open('[Link]', 'w') as f:
-> [Link]('Hello, World!')
7. How to sort a list in descending order?
-> sorted_list = sorted([4, 2, 8, 1], reverse=True)
8. How to create a dictionary in Python?
-> my_dict = {'name': 'Alice', 'age': 25}
9. How to iterate over a dictionary?
-> for key, value in my_dict.items():
-> print(key, value)
10. How to use list comprehension to create a list of squares?
-> squares = [x**2 for x in range(1, 6)]