Double Iteration in List Comprehension

Suppose you have a text full of sentences and you want an array of words. # Without list comprehension list_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 … Read more

Flattening a shallow list in Python [duplicate]

If you’re just looking to iterate over a flattened version of the data structure and don’t need an indexable sequence, consider itertools.chain and company. >>> list_of_menuitems = [[‘image00’, ‘image01’], [‘image10’], []] >>> import itertools >>> chain = itertools.chain(*list_of_menuitems) >>> print(list(chain)) [‘image00’, ‘image01’, ‘image10′] It will work on anything that’s iterable, which should include Django’s iterable … Read more

Generator expressions vs. list comprehensions

John’s answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it’s also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won’t work: def gen(): return (something for something in get_some_stuff()) print … Read more

Create a dictionary with comprehension

Use a dict comprehension (Python 2.7 and later): {key: value for (key, value) in iterable} Alternatively for simpler cases or earlier version of Python, use the dict constructor, e.g.: pairs = [(‘a’, 1), (‘b’, 2)] dict(pairs) #=> {‘a’: 1, ‘b’: 2} dict([(k, v+1) for k, v in pairs]) #=> {‘a’: 2, ‘b’: 3} Given separate … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)