DEV Community

SK RAJIBUL
SK RAJIBUL

Posted on

Python's Power: Mastering Everyday Coding Tasks

πŸš€ Unlocking Python's Power: Mastering Everyday Coding Tasks!

πŸ” Let's dive into the realm of Python one-liners, where a single line of code packs a powerful punch! πŸ’₯ Here are some nifty tricks to streamline your coding tasks:

  • Read Lines from a File: πŸ“„ Accessing file content effortlessly!

lines = [line.strip() for line in open('example.txt')]

Enter fullscreen mode Exit fullscreen mode
  • Count Lines in a File: πŸ“ Keeping track of file length like a pro!

line_count = sum(1 for line in open('example.txt'))

Enter fullscreen mode Exit fullscreen mode
  • List Comprehension with Conditional: 🌟 Filtering lists with ease!

filtered_list = [x for x in my_list if x > 0]

Enter fullscreen mode Exit fullscreen mode
  • Calculate Average of a List: πŸ“Š Math made simple!

average = sum(my_list) / len(my_list) if len(my_list) > 0 else 0

Enter fullscreen mode Exit fullscreen mode
  • Conditional Value Assignment: 🎯 Let Python make decisions for you!

result = x if condition else y

Enter fullscreen mode Exit fullscreen mode
  • Handle Zero Division Error: ⚠️ Avoiding pitfalls gracefully!

result = numerator / denominator if denominator != 0 else 0

Enter fullscreen mode Exit fullscreen mode
  • Fetch HTML Content with Requests: 🌐 Bringing web data to your fingertips!

import requests; html_content = requests.get('https://example.com').text

Enter fullscreen mode Exit fullscreen mode
  • Multithreading with threading Module: πŸš€ Boosting performance with parallelism!

import threading; threading.Thread(target=my_function).start()

Enter fullscreen mode Exit fullscreen mode
  • Hashing with hashlib: πŸ”’ Keeping passwords secure with hashing!

import hashlib; hashed_password = hashlib.sha256(password.encode()).hexdigest()

Enter fullscreen mode Exit fullscreen mode
  • Check if a key exists in a dictionary: πŸ—οΈ Navigating dictionaries like a seasoned explorer!

is_present = 'key' in {'key': 'value'}

Enter fullscreen mode Exit fullscreen mode
  • Removing duplicates from a list while preserving order: πŸ”„ Keeping things tidy without losing track!

unique_list = list(dict.fromkeys([1, 2, 2, 3, 4]))

Enter fullscreen mode Exit fullscreen mode
  • Download a file from a URL: πŸ“₯ Fetching files with finesse!

urllib.request.urlretrieve("https://lnkd.in/gsGhU6f7", "downloaded_file.zip")

Enter fullscreen mode Exit fullscreen mode
  • List files in a directory: πŸ“‚ Exploring directories with Python's directory prowess!

files = [f for f in os.listdir("path/to/dir") if os.path.isfile(os.path.join("path/to/dir", f))]

Enter fullscreen mode Exit fullscreen mode

Top comments (0)