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 way
numbers = []
for i in range(10):
numbers.append(i * 2)

Do this:

# The Pythonic way
numbers = [i * 2 for i in range(10)]

2. F-strings > Format#

name = "LUKKID"
years = 3
# Old way
print("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 this
for i in range(len(fruits)):
print(i, fruits[i])
# Do this instead
for i, fruit in enumerate(fruits):
print(i, fruit)

4. Dictionary Get Method#

user = {'name': 'LUKKID'}
# This might crash
# age = user['age'] # KeyError!
# This is safe
age = user.get('age', 'Unknown') # Returns 'Unknown'

5. Context Managers for Files#

# Always use 'with' for files
with open('data.txt', 'r') as file:
content = file.read()
# File automatically closes!

6. Virtual Environments#

Terminal window
# Always use venv!
python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows

Bonus: My Favorite Libraries#

LibraryUse Case
requestsHTTP calls
pandasData analysis
flaskWeb APIs
discord.pyDiscord bots
seleniumWeb automation

Python is still my favorite!

Python Tips I Wish I Knew Earlier
https://blog.lukkid.dev/posts/python-tips/
Author
LUKKID
Published at
2024-02-05
License
CC BY-NC-SA 4.0