6. Set comprehension
Set comprehensions are a concise way to build sets from iterables.
Like other comprehension forms, it puts the result shape front and center while leaving Python to manage the accumulation details. That makes it especially readable when uniqueness is part of the goal.
6.1. Don’t do this
1words = ['i', 'like', 'to', 'eat', 'pizza', 'and', 'play', 'tennis']
2
3vocab = set()
4
5for word in words:
6 vocab.add(word)
6.2. Do this
1words = ['i', 'like', 'to', 'eat', 'pizza', 'and', 'play', 'tennis']
2
3vocab = {word for word in words}