Tutorial: List Comprehensions in Python

lattyware · 16K views · 2012 · 5:41

Open on YouTube

Python, Ruby & scripting languagesEducation & learningtutorial

Why Stack Overflow recommends it

Stack Overflow users, often the video's author himself, link it as the go-to explanation whenever an answer replaces a loop with a list, set, dict comprehension or generator expression.

Recommended by 2 people across 11 different months, 2012 to 2020.

What it is

A roughly six minute Python tutorial by lattyware (Gareth Latty) explaining list comprehensions, plus set and dictionary comprehensions and generator expressions. It is a screencast in PyCharm, updated from an earlier version with better audio and a few extra tips.

What people said

Strong rec Gareth Latty · 2013-02 · Stack Overflow · on “Why can't I change or reassign the values of variables in lists using a for loop (python)?”

This is because you only get a reference to the variable in the list. When you replace it, you simply change what that reference is pointing to, so the item in the list is left unchanged. The best explanation for this is to follow it visually [LINK] - step through the execution visualization found at that link and it should be very clear. Note that mutable objects can be mutated in place, and that will affect the list (as the objects themselves will have changed, not just what the name you are working with is pointing to). For comparison, see the visualization here [LINK] . The best option here is a list comprehension [this video] . new_list = [num + 1 for num in old_list]

Recommends Amber · 2012-12 · Stack Overflow · on “string indices must be integers error in python, but indices are integers”

The immediate issue You probably meant to use S[0:a] and S[a:len(S)] (slicing) rather than commas. A note about slicing... You don't have to specify the leading zero or the trailing len(S) there - they're implicit. So you could just use S[:a] and S[a:] to mean the same thing. Also note that S[0:a] + S[a:len(S)] is equivalent to S . You probably didn't want to include the + in there, so you'd probably want to use S[a+1:len(S)] instead. Another note about finding the position of a character in a string You don't need to loop over the indices manually - there's already the .index() method of strings to do this: >>> "hello".index("e") 1 A simpler way to accomplish your overall goal You can just

Recommends Gareth Latty · 2012-12 · Stack Overflow · on “Check if all the elements in that list are divisible by some given integer or not”

First of all, you want modulo division ( % ) as you want to see if it evenly divides by 5 , so you are checking for a remainder, not the result of division. You can use the all() builtin [LINK] (which does what it says on the tin), but you don't need to generate a list, instead use a generator expression [this video] : all(x%5 == 0 for x in l) This has the advantage of being lazy, so as soon as a value isn't divisible it will return, saving computation

Recommends Gareth Latty · 2012-12 · Stack Overflow · on “Iterative deletion from list (Python 2)”

One problem here is that i is the item from the list, not it's index. So when you do del fiblist[i] you are not removing i , but the value that is at index i (which doesn't exist so you get an error). This can be fixed by using enumerate() to get indices to use, however, doing so introduces a new problem. The main issue here is that you can't modify the length of a list while you iterate over it, as it messes with Python's iteration. One solution would be to copy the list and work on a copy, but the better one is to use a list comprehension [this video] to do what you want: [i for i in fiblist if i%2 == 0] This produces a new list with only the elements you want in. List comprehensions are a powe

Recommends Gareth Latty · 2012-12 · Stack Overflow · on “How do I make a 'while' loop print the results of the loop's conditional into a single line(concatenated)?”

First of all, using a while loop here isn't optimal, instead, use a for loop, which is designed to loop over iterators like data structures (a string is just a sequence of characters): for character in x: print(test[character]) Then instead of printing the characters, store them in a list. characters = [] for character in x: characters.append(str(test[character])) We can then join those into a single string (we made the numbers strings earlier to make this step easier), and make an int from that string: int("".join(characters)) Python supports an easier way to do this kind of list construction - the list comprehension [this video] : characters = [str(test[character]) for character in x] This prod

Recommends Gareth Latty · 2012-12 · Stack Overflow · on “Python: List Dictionary Comprehension”

Well, first of all, this is a rather bad way of doing it. Looping by indices is a really bad practice in Python (it's slower, and horrible to read), so the much better way is this: letters = 'defghijklmno' K = {letter: (i*i-1) for i, letter in enumerate(letters)} All this is is a simple dictionary comprehension [this video] . When we loop over a string, we get the individual characters making it up. We use the enumerate() builtin to give us matching numbers, and then produce a dictionary from the letter to the number squared, minus one. If you are struggling with the comprehension itself, it's equivalent to a for loop (except faster), and I recommend you watch my video [this video] for a complete expl

Recommends Gareth Latty · 2012-12 · Stack Overflow · on “Need a way to pull out use an element from a list as a variable”

You can do this, but the real question is, should you? The answer is, quite simply, no. Dynamic variable names are a recipe for trouble, and you are much better off using a dictionary. It will make your code simpler, not more complex. One simply does: data['xx'][0] Use the csv module [LINK] to load in your data, then construct a dictionary. This can be a simple dictionary comprehension [this video] : with open('data.csv') as file: reader = csv.reader(file) data = {key: values for key, *values in reader} If you really need the order, then you can use collections.OrderedDict [LINK] to do the job. data = collections.OrderedDict((key, values) for key, *values in reader) Do note that this nice unpacki

Recommends Gareth Latty · 2013-01 · Stack Overflow · on “How to break a Python while loop from a function within the loop”

Python has a cool feature in generators - these allow you to easily produce iterables for use with a for loop, that can simplify this kind of code. def input_until(message, func): """Take raw input from the user (asking with the given message), until when func is applied it returns True.""" while True: value = raw_input(message) if func(value): return else: yield value for value in input_until("enter input: ", lambda x: x == "exit"): ... The for loop will loop until the iterator stops, and the iterator we made stops when the user inputs "exit" . Note that I have generalised this a little, for simplicity, you could hard code the check against "exit" into the generator, but if you need similar

Recommends Gareth Latty · 2013-01 · Stack Overflow · on “Looping a Python split function”

What you want is to build up a new list, by modifying the elements of an old one, fortunately, Python has the list comprehension [this video] - perfect for this job. with open("domainlist.txt", "r") as datafile: modified = ['.'.join(x.split('.')[-2:]) for x in datafile] This behaves exactly like creating a list and adding items to it in a for loop, except faster and nicer to read. I recommend watching the video linked above for more information on how to use them. Note that file.read() reads the entire thing in as one big string, what you wanted was probably to loop over the lines of the file, which is done just by looping over the file itself. Your current loop loops of the individual characters

Recommends Gareth Latty · 2013-02 · Stack Overflow · on “Unable to filter in python using lambda”

Note that where using `filter()` with `lambda`, you are better off with a list comprehension [this video] . E.g: `[x for x in languages if x == "Python"]`.