15 Python tips and tricks, so you don’t have to look them up on Stack Overflow

George Seif
Jul 23 · 2 min read

Tired of searching on Stack Overflow every time you forget how to do something in Python? Me too!

Here are 15 python tips and tricks to help you code faster!

(1) Swapping values

x, y = 1, 2
print(x, y)
x, y = y, x
print(x, y)

(2) Combining a list of strings into a single one

sentence_list = ["my", "name", "is", "George"]
sentence_string = " ".join(sentence_list)

(3) Splitting a string into a list of substrings

sentence_string = "my name is George"

(4) Initialising a list filled with some number

[0]*1000 # List of 1000 zeros 
[8.2]*1000 # List of 1000 8.2's

(5) Merging dictionaries

x = {'a': 1, 'b': 2}
y = {'b': 3, 'c': 4}
z = {**x, **y}

(6) Reversing a string

name = "George"

(7) Returning multiple values from a function

def get_a_string():
a = "George"
b = "is"
c = "cool"
return a, b, c
sentence = get_a_string()
(a, b, c) = sentence

(8) List comprehension

a = [1, 2, 3]
b = [num*2 for num in a] # Create a new list by multiplying each element in a by 2

(9) Iterating over a dictionary

m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} 
for key, value in m.items():
print('{0}: {1}'.format(key, value))

(10) Iterating over list values while getting the index too

m = ['a', 'b', 'c', 'd']
for index, value in enumerate(m):
print('{0}: {1}'.format(index, value))

(11) Initialising empty containers

a_list = list()
a_dict = dict()
a_map = map()
a_set = set()

(12) Removing useless characters on the end of your string

name = "  George "
name_2 = "George///"
name.strip() # prints "George"
name_2.strip("/") # prints "George"

(13) Find the most frequent element in a list

test = [1, 2, 3, 4, 2, 2, 3, 1, 4, 4, 4]
print(max(set(test), key = test.count))

(14) Check the memory usage of an object

import sys
x = 1

(15) Convert a dict to XML

from xml.etree.ElementTree import Elementdef dict_to_xml(tag, d):
Turn a simple dict of key/value pairs into XML
elem = Element(tag)
for key, val in d.items():
child = Element(key)
child.text = str(val)
return elem

Like to learn?

Follow me on twitter where I post all about the latest and greatest AI, Technology, and Science! Connect with me on LinkedIn too!

Recommended Reading

Want to learn more about coding in Python? The Python Crash Coursebook is the best resource out there for learning how to code in Python!

And just a heads up, I support this blog with Amazon affiliate links to great books, because sharing great books helps everyone! As an Amazon Associate I earn from qualifying purchases.

George Seif

Written by

Certified Nerd

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade