Saturday 11 November 2023

20 extremely useful single-line Python codes

 





#!/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

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (118) C (77) C# (12) C++ (82) Course (62) Coursera (180) Cybersecurity (22) data management (11) Data Science (95) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (4) Pandas (3) PHP (20) Projects (29) Python (753) Python Coding Challenge (232) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses