Sitemap
Muhammad Shoaib Ali

Muhammad Shoaib Ali

Python Code tips

2 min readJul 23, 2022

--

Python code tips for memory and faster computation

Iterate with enumerate

When we need to iterate list with index and value then use If you need to iterate with enumerate instead of range(len(x)) which returns index and value as tuple.

List comprehension

Use list comprehension with instead of formal loop which includes powerful loop and if else statement. let’s see in below example which calculates square of each number from 0–9.

Sort timetables

If you need to sort a list, tuple, dictionary or complex iterables use built in sorted(x) function which will sort in ascending by default. it can be sorted reverse by setting sorted(x, reverse=True) . Dictionary can be sorted by setting key as function here we are sorting by ‘age’.

Store unique values

In stead of writing unique values in a list put list into a set which removes duplicate values.

Get Muhammad Shoaib Ali’s stories in your inbox

Join Medium for free to get updates from this writer.

Save memory with generators comprehension

list comprehension is always good but when we are dealing with large amount of data then generators save lot of memory. here in this example we are generating sum of 10k numbers wit generator is only 112bytes but with list comprehension is 85k bytes.

get set dictionary items

we can set some dictionary without crashing with key error by using .get() method which returns default value None without raising an error. we can also update dictionary with .setdefault(key, value) .

use collections.counter

If we need to count values in hashable objects like in list. It returns optimized count for each item. we can also get count for most common item with .most_common method which returns tuple with key and count.

String formatting

In python 3.6 we can format string and print with specific no of floating digits to be printed.

--

--