Skip to main content

A Hundred Days of Code, Day 018 - Python Comprehensions, Done!

Continuing my comprehensions journey.
Hopefully it makes more sense this time around

Notes

Set Comprehensions

  • If I want a set of uniques from a group, I could use a set.
    • Or like Reuven likes to joke, a set is a dictionary with no values; an immoral dictionary 😂
  • Create it with a somesetcomp = set('somecondition' for a something in somethingbig) or in a simpler manner, somesetcomp = {'somecondition' for something in somethingbig}
    • Protip, better to start with a list comprehension, be done with figuring out stuff and then just switch the brackets at the end. Fewer issues that way.

Dictionary Comprehensions

  • Create it like so somedictcomp = {somekey:somevalue for something in somethingbig}
  • It creates only one dictionary, not a set
  • It has to have a key and a value variable, seperated by a colon. If it is just a single variable, I’ll end up with a set comprehension.

Nested Comprehensions

  • Running a comprehension on the elements of a parent comphrehension is a nested comprehension.
    • For e.g. if I had a list of lists and I needed to pull out each element from each list I would
      • create a comprehension that would get each list from my giant list of lists
      • and then run a comprehension on those lists to get each element out.
      • big_list = [[10, 20], [30, 40], [50, 60], [70, 80]]
      • elemental_list = [each_element for each_list in big_list for each_element in each_list]
  • Pretty handy when needed. I can go as many levels deep as needed.

Why Comprehensions?

  • A comprehension is needed or rather the better tool for the job, when I have one sequence and I want to turn it into another sequence. Creating new things from old things
  • If I am interested in the side effects, the actions, umm, like printing to the screen for example, that is when I’d use for loops.
  • It gets increasingly obvious, the more I use it.

Read all about my Python Comprehensions journey here