3 ms·
For loops can often be avoided. I would write this particular example in one of these ways, that I think are readable: x = [] for word in words:
by rbonvall 12y ago
For loops can often be avoided. I would write this particular example in one of these ways, that I think are readable:
x = []
for word in words:
x.extend(word)
from itertools import chain
x = [letter for letter in chain(*words)]
x = list(chain(*words))
- YokoZar 12y agoWouldn't chain(*words) require unpacking all of words before feeding it into the chain function, storing a second copy of the word list in memory?
- rbonvall 12y agoYes it would, but I don't care about these small efficiencies, say 97% of the time ;) The lazy version in Python 3 would be this one: list(chain(*map(iter, words))) For Python 2 one has to use itertools.imap instead of map.