Back
Close

Computing with Data

elgeish
34.9K views
Previous: Hashable Objects Next: Set Comprehensions

List Comprehensions

For many constructs in Python, there's a dull way of doing things, and then there's the Pythonic way:

from collections import Counter
# Example: a simple, mundane transformation to a list
words = ['apple', 'banana', 'carrot']
modes = []
for word in words:
counter = Counter(word)
# most_common(n) returns a list and the *
# operator expands it before calling append(x)
modes.append(*counter.most_common(1))
print(modes)
# Example: the Pythonic way (using a list comprehension)
print([Counter(w).most_common(1)[0] for w in words])
# Example: select and transform
print([Counter(w).most_common(1)[0] \
for w in words if len(w) > 5])
# Example: mimicing nested for loops and multiple conditionals
x = (0, 1, 2, 7)
y = (9, 0, 5)
print([(a, b) for a in x for b in y if a != 0 and b != 0])
# alternatively
print([(a, b) for a in x if a != 0 for b in y if b != 0])
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants