2 minute read

  1. Check if a string is empty:

    if not my_string:
        print("String is empty")
  2. Sort a dictionary by value:

    sorted_dict = dict(sorted(my_dict.items(), key=lambda x: x[1]))
  3. Merge two dictionaries:

  4. Flatten a list of lists:

    flattened_list = [item for sublist in my_list for item in sublist]
  5. Check if a list contains duplicates:

    if len(my_list) != len(set(my_list)):
        print("List contains duplicates")
  6. Reverse a string:

    reversed_string = my_string[::-1]
  7. Get the current date and time:

    import datetime
    now = datetime.datetime.now()
  8. Get the file extension from a file path:

    file_extension = os.path.splitext(file_path)[1]
  9. Convert a string to a boolean:

    my_bool = my_string.lower() in ['true', 't', 'yes', 'y', '1']
  10. Remove duplicates from a list while preserving order
      seen = set()
      unique_list = [x for x in my_list if x not in seen and not seen.add(x)]
  11. Convert a list of strings to a single string:

      my_string = ' '.join(my_list)
  12. Generate a random number:

      import random
      random_number = random.randint(min_value, max_value)
  13. Get the size of a file:

      file_size = os.path.getsize(file_path)
  14. Replace all occurrences of a substring in a string:

      new_string = my_string.replace(substring, new_substring)
  15. Get the last N elements of a list:

      last_n_elements = my_list[-n:]
  16. Filter a list based on a condition:

      filtered_list = [x for x in my_list if condition(x)]
  17. Check if a file exists:

      if os.path.isfile(file_path):
          print("File exists")
  18. Read a file line by line:

      with open(file_path) as f:
          for line in f:
  19. Get the current working directory:

      current_directory = os.getcwd()
  20. Create a directory if it does not exist:

      if not os.path.exists(directory_path):
  21. Creating a dictionary from two lists:

    keys = ['a', 'b', 'c']
    values = [1, 2, 3]
    my_dict = dict(zip(keys, values))
  22. Checking if a file exists:

    import os
    if os.path.exists('/path/to/file.txt'):
        # do something
  23. Getting the current date and time:

    from datetime import datetime
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
  24. Reversing a string:

    my_string = "Hello, world!"
    reversed_string = my_string[::-1]
  25. Generating a random number:

    import random
    my_number = random.randint(1, 100)
  26. Converting a string to a list:

    my_string = "apple,banana,orange"
    my_list = my_string.split(",")
  27. Sorting a list of dictionaries by a specific key:

    my_list = [{'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 20}]
    sorted_list = sorted(my_list, key=lambda x: x['age'])
  28. Removing duplicates from a list:

    my_list = [1, 2, 3, 2, 1]
    my_list = list(set(my_list))
  29. Checking if a string contains a substring:

    my_string = "Hello, world!"
    if "world" in my_string:
        # do something
  30. Joining a list of strings into a single string:

      my_list = ['apple', 'banana', 'orange']
      my_string = ', '.join(my_list)

That’s all for today! Cheers!!!

You can also read my other posts in python:

  1. Machine Learning: Multiclass Classification Template for any Classification Dataset
  2. Cyber Security (in Python) Books, Codes, and other Resource Collection available on GitHub
  3. Write a Reverse Proxy Server in Python: Part 1 (Reverse Proxy Server)
  4. Add Custom Headers to Python Files in Seconds using VSCode Editor
  5. How to Write a RESTful API using Python Flask to fetch data from PostgreSQL Database
  6. Python ZeroMQ Module: A Simple Publisher-Subscriber Chat Application
  7. Python Logging: Basic Tutorial and Template
  8. Creating and Reading QR Code in Python: A Simple Python Class using qrcode and opencv module
  9. A Curated list of Python Cheatsheets Collections
  10. How to write a Twitter Data Scrapper in Python
  11. Useful Functions of Python Itertools Module
  12. Collection of Data Science in Python Posts in my Blog
  13. Introduction to Deep Learning in Python (Keras and Tensorflow) using the MNIST Dataset

Leave a comment