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.
Table of Contents
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']
Class & Object
Create Static Variables —
//use staticmethod() class Student: def showAge(birthdate): print(birthdate) Student.showAge = staticmethod(Student.showAge) Student.showAge("1980-01-01") //use @staticmethod decorator class Student: @staticmethod def showAge(birthdate): print(birthdate) Student.showAge("2000-05-26")
Datetime
Last Day of a Month —
import calendar month_range = calendar.monthrange(2022, 1) print(month_range) # (5, 31) month_range = calendar.monthrange(2022, 2) print(month_range) # (1, 28) month_range = calendar.monthrange(2022, 5) print(month_range) # (6, 31) last_day = month_range[1] month_range = calendar.monthrange(2022, 8) print(month_range) # (0, 31)