#!/usr/bin/env python
# coding: utf-8
# # 20 extremely useful single-line Python codes
# # 1. Swap Variables:
# In[ ]:
a, b = b, a
# # 2. Find Maximum Element in a List:
# In[ ]:
max_element = max(lst)
# # 3. Find Minimum Element in a List:
# In[ ]:
min_element = min(lst)
# # 4. List Comprehension:
# In[ ]:
squared_numbers = [x**2 for x in range(10)]
# # 5. Filter List Elements:
# In[ ]:
even_numbers = list(filter(lambda x: x % 2 == 0, lst))
# # 6. Map Function:
# In[ ]:
doubled_numbers = list(map(lambda x: x * 2, lst))
# # 7. Sum of List Elements:
# In[ ]:
total = sum(lst)
# # 8. Check if All Elements in a List are True:
# In[ ]:
all_true = all(lst)
# # 9. Check if Any Element in a List is True:
# In[ ]:
any_true = any(lst)
# # 10. Count Occurrences of an Element in a List:
# In[ ]:
count = lst.count(element)
# # 11. Reverse a String:
# In[ ]:
reversed_str = my_str[::-1]
# # 12. Read a File into a List of Lines:
# In[ ]:
lines = [line.strip() for line in open('file.txt')]
# # 13. Inline If-Else:
# In[ ]:
result = "even" if x % 2 == 0 else "odd"
# # 14. Flatten a Nested List:
# In[ ]:
flat_list = [item for sublist in nested_list for item in sublist]
# # 15. Find the Factorial of a Number:
# In[ ]:
factorial = 1 if n == 0 else functools.reduce(lambda x, y: x * y, range(1, n+1))
# # 16. List Unique Elements:
# In[ ]:
unique_elements = list(set(lst))
# # 17. Execute a Function for Each Element in a List:
# In[ ]:
result = list(map(lambda x: my_function(x), lst))
# # 18. Calculate the Average of a List:
# In[ ]:
average = sum(lst) / len(lst) if len(lst) > 0 else 0
# # 19. Convert a String to a List of Characters:
# In[ ]:
char_list = list("hello")
# # 20. Find Common Elements Between Two Lists:
# In[ ]:
common_elements = list(set(lst1) & set(lst2))
# In[ ]:
0 Comments:
Post a Comment