20 Essential Python Code Snippets to Boost Your Programming Skills

This article presents twenty practical Python code snippets that demonstrate common tasks—from building a simple HTTP server and manipulating lists and dictionaries to reading CSV files, creating classes, and performing memory profiling—providing developers with ready-to-use examples to enhance their coding efficiency.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
20 Essential Python Code Snippets to Boost Your Programming Skills

This article presents twenty practical Python code snippets that demonstrate common tasks—from building a simple HTTP server and manipulating lists and dictionaries to reading CSV files, creating classes, and performing memory profiling—providing developers with ready-to-use examples to enhance their coding efficiency.

1. Simple HTTP Web Server

# Simple HTTP SERVER
import socketserver
import http.server
PORT = 8000
handler = http.server.SimpleHTTPRequestHandler
with socketserver.TCPServer(("", PORT), handler) as http:
    print("Server Launch at Localhost: " + str(PORT))
    http.serve_forever()
# Type in http://127.0.0.1:8000/ in your webbrowser

2. One‑Liner Loop Through List

# One Liner Loop through List
mylist = [10, 11, 12, 13, 14]
print([i * 2 for i in mylist])  # [20, 22, 24, 26, 28]
print([i * 5 for i in mylist])  # [50, 55, 60, 65, 70]

3. Update Dictionary

# Update Dictionary
mydict = {1: "Python", 2: "JavaScript", 3: "Csharp"}
mydict.update({4: "Dart"})
print(mydict)  # {1: 'Python', 2: 'JavaScript', 3: 'Csharp', 4: 'Dart'}

4. Split Multi‑Line String

# Split Multi Lines String
string = "Data 
 is encrpted 
 by Python"
print(string)
# Output
# Data
# is encrpted
# by Python
splited = string.split("
")
print(splited)  # ['Data ', ' is encrpted ', ' by Python']

5. Track Frequency

# Track Frequency
import collections

def Track_Frequency(lst):
    return dict(collections.Counter(lst))

print(Track_Frequency([10, 10, 12, 12, 10, 13, 13, 14]))
# Output
# {10: 3, 12: 2, 13: 2, 14: 1}

6. Read CSV Without Pandas

# Simple CSV Reading
import csv
with open("Test.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
# Example Output
# ['Sr', 'Name', 'Profession']
# ['1', 'Haider Imtiaz', 'Back End Developer']
# ['2', 'Tadashi Wong', 'Software Engineer']

7. Squash List of Strings

# Squash list of String
mylist = ["I learn", "Python", "JavaScript", "Dart"]
string = " ".join(mylist)
print(string)  # I learn Python JavaScript Dart

8. Get Index of Element in List

# Get Index of Element in List
mylist = [10, 11, 12, 13, 14]
print(mylist.index(10))  # 0
print(mylist.index(12))  # 2
print(mylist.index(14))  # 4

9. Magic of *arg

# Magic of *arg
def func(*arg):
    num = 0
    for x in arg:
        num = num + x
    print(num)  # 600

func(100, 200, 300)

10. Get Type of Any Data

# Get Type of Any Data
data1 = 123
data2 = "Py"
data3 = 123.443
data4 = True
data5 = [1, 2]
print(type(data1))  # <class 'int'>
print(type(data2))  # <class 'str'>
print(type(data3))  # <class 'float'>
print(type(data4))  # <class 'bool'>
print(type(data5))  # <class 'list'>

11. Modified Print Function

# Modified Print Function
print("Top Programming Languages are %r, %r and %r" % ('Py', 'Js', 'C#'))
# Output
# Top Programming Languages are 'Py', 'Js' and 'C#'

12. Decapitalize String

# Decapitation of String
data1 = "ABCD"
data2 = "Py"
data3 = "Learn Coding"
print(data1.lower())  # abcd
print(data2.lower())  # py
print(data3.lower())  # learn coding

13. Quick Variable Swap

# Quick Way to Exchange Variables
d1 = 25
d2 = 50
d1, d2 = d2, d1
print(d1, d2)  # 50 25

14. Print with Separation

# Print with Separation
print("Py", "Js", "C#", sep="-")  # Py-Js-C#
print("100", "200", "300", sep="x")  # 100x200x300

15. Fetch Webpage HTML

# First Install Request with pip install requests
import requests
r = requests.get("https://medium.com/@codedev101")
print(r)  # Whole page html data will display

16. Get Memory Used by Data

# Get Memory taken by data
import sys

def memory(data):
    return sys.getsizeof(data)

print(memory(100))          # 28
print(memory("Pythonnnnnnn"))  # 61

17. Simple Class Creation

# Simple Class Creation
class Employee:
    def __init__(self, empID):
        self.empID = empID
        self.name = "Haider"
        self.salary = 50000
    def getEmpData(self):
        return self.name, self.salary

emp = Employee(189345)
print(emp.getEmpData())  # ('Haider', 50000)

18. String Multiplier

# String Multiplier
# Normal way
for x in range(5):
    print("C#")
# Good way
print("C# " * 5)  # C# C# C# C# C#

19. Chain Comparison

# Chain Comparison
a = 5
print(1 == a < 2)  # False
print(2 < 3 < 6 > a)  # True

20. Digitizing an Integer

# Digitizing
integer = 234553
digitz = [int(i) for i in str(integer)]
print(digitz)  # [2, 3, 4, 5, 5, 3]

These snippets illustrate concise, reusable patterns that can accelerate everyday Python development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythontutorialcode snippetsbasics
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.