top of page

Dictionary and List Comprehension

Introduction


No one likes confusing code.

Luckily for us, we have comprehension.


Comprehension is a concept in Python that generally revolves around condensing or abstracting away code from sequences like dictionaries and lists.


Today, we'll go over two comprehension methods through which you can condense such sequences in programs of your own.


List Comprehension


Suppose I had a function that stores all instances of even numbers passed as arguments within a list:

def evenNums(*nums):
	evens = []
	for num in nums:
		if (num % 2 == 0):
			evens.append(num)
	return evens

But right now, it's a bit clunky. With comprehension, we can reduce this unnecessary jargon to just a couple of lines:

def returnEvens(*nums):
	evens = [num for num in nums if num % 2 == 0]
	return evens

print(returnEvens(1, 2, 4))	# Output: [2, 4]

Note that *nums is just a way of telling our program that we expect an unknown number of arguments. These arguments will be converted to a tuple.


Now, not only is it much cleaner, but it's equally (if not more) readable.


Basically, our function adds num, a list element, to the list evens, if and only if that num is even. This process continues for all elements in nums.


Dictionary Comprehension


Similarly, we can use comprehension with dictionaries, as well. As a dummy function, let's say I wanted to store all of the squares of odd numbers within some dictionary to another dictionary:

def oddSquares(**nums):
	oddsDict = {}
	for key, num in nums:
		if (num % 2 == 1):
			oddsDict[key] = num ** 2
	return oddsDict

Condensed...

def oddSquares(**nums):
	oddsDict = {key : num ** 2 for key, num in nums.items() if num % 2 == 1)
	return oddsDict

print(oddSquares(num1=3, num2=6, num3=5)	# Output: {'num1': 9, 'num3': 25}

*Note that **nums means the function takes a dictionary with an arbitrary number of elements as a parameter.


Here, we:

  • specified the key and the value that would go into the new dictionary separated by a column

  • looped over the nums dictionary and gathered its keys and values

  • added the square to the list if and only if num was odd


Final Thoughts


Hopefully now you're equipped to use comprehension for abstracting away unnecessary code, creating a cleaner and more readable program. Thanks for reading!

I value your feedback.
Drop a line to let me know what you think.

  • LinkedIn
  • Instagram

Thanks for Reaching Out!

© 2035 Sabir Seth. All Rights Reserved.

bottom of page