Double Iteration in List Comprehension
I hope this helps someone else since
a,b,x,y don't have much meaning to me! Suppose you have a text full of sentences and you want an array of words.
# Without list comprehensionlist_of_words = for sentence in text: for word in sentence: list_of_words.append(word)return list_of_words
I like to think of list comprehension as stretching code horizontally.
Try breaking it up into:
# List Comprehension [word for sentence in text for word in sentence]
"Hi", "Steve!"), ("What's", "up?")) [word for sentence in text for word in sentence]['Hi', 'Steve!', "What's", 'up?']text = ((
This also works for generators
"Hi", "Steve!"), ("What's", "up?")) gen = (word for sentence in text for word in sentence)for word in gen: print(word)HiSteve!What'sup?text = ((
To answer your question with your own suggestion:
for b in a for x in b] # Works fine[x
While you asked for list comprehension answers, let me also point out the excellent itertools.chain():
from itertools import chainlist(chain.from_iterable(a))list(chain(*a)) # If you're using python < 2.6