Python Code Snippets

Python is a versatile language that you can use on the backend, frontend, or full stack of a web application. It’s also used in data science and machine learning applications. Python is a high-level, interpreted, general-purpose programming language with a focus on code readability.

Python is one of the most popular programming languages in the world. It’s used in a variety of applications, from web development to data science. Python is easy to learn for beginners and has many resources available online.

If you’re looking for a roundup of some useful Python code snippets, you’ve come to the right place. In this post, we’ll share some handy code examples that will help you get up and running with Python. Whether you’re a beginner or an experienced developer, these snippets will come in handy.

Curated List of Python Code Snippets

Array & List

Sum a Column's Values in a List
sales = [
    {'product': 'CHINESE Burning Blue', 'price': 152.25}, 
    {'product': 'CHINESE Burning Charms', 'price': 100.00}, 
    {'product': 'Crystal BEADED', 'price': 16.75}, 
    {'product': 'Crystal Ring', 'price': 78.00}, 
]
total_price = sum([sale['price'] for sale in sales])
print(total_price)
# output: 347.0
Extract a Column From a List
keyboards = [['q', 'w', 'r'],
            ['a', 's', 'd'],
            ['z', 'x', 'c']]
first_col = [row[0] for row in keyboards]
print(first_col) #output: ['q', 'a', 'z']

brands = [{'label': 'Samsung', 'model': '121312412'}, {'label': 'Apple', 'model': '789615'}]
labels = [brand['label'] for brand in brands]
print(labels ) #output: ['Samsung', 'Apple']

Datetime

Calculate Age from Birthday
from datetime import date

today = date.today()
age = today.year - born.year - ((today.month, today.day) < (born.month, born.day))
Subtract Dates and Times
start_date = datetime.date(2022, 5, 1)
end_date = datetime.date(2022, 5, 14)

result = end_date - start_date

Leave a Comment

Your email address will not be published.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close