193 words
1 minute
Python Tips I Wish I Knew Earlier
Python Tips I Wish I Knew Earlier
Python was my first language, and after years of using it, here are tips I wish someone told me from the start.
1. List Comprehensions
Instead of this:
# The old waynumbers = []for i in range(10): numbers.append(i * 2)Do this:
# The Pythonic waynumbers = [i * 2 for i in range(10)]2. F-strings > Format
name = "LUKKID"years = 3
# Old wayprint("Hi, I'm {} with {} years exp".format(name, years))
# New way (Python 3.6+)print(f"Hi, I'm {name} with {years} years exp")3. Use Enumerate
fruits = ['apple', 'banana', 'orange']
# Don't do thisfor i in range(len(fruits)): print(i, fruits[i])
# Do this insteadfor i, fruit in enumerate(fruits): print(i, fruit)4. Dictionary Get Method
user = {'name': 'LUKKID'}
# This might crash# age = user['age'] # KeyError!
# This is safeage = user.get('age', 'Unknown') # Returns 'Unknown'5. Context Managers for Files
# Always use 'with' for fileswith open('data.txt', 'r') as file: content = file.read()# File automatically closes!6. Virtual Environments
# Always use venv!python -m venv myenvsource myenv/bin/activate # Linux/Macmyenv\Scripts\activate # WindowsBonus: My Favorite Libraries
| Library | Use Case |
|---|---|
| requests | HTTP calls |
| pandas | Data analysis |
| flask | Web APIs |
| discord.py | Discord bots |
| selenium | Web automation |
Python is still my favorite!
Python Tips I Wish I Knew Earlier
https://blog.lukkid.dev/posts/python-tips/