• entries
  • comments
  • views

Python List Comprehensions! (And Python / Pygame Update!)

Sign in to follow this  


Some news:

I finished Code Academy's Python track and most of their advanced non-track courses.

I've started hacking around with Pygame.

I'm finally making games again!

That last piece of news might be a surprise. I've spent most of the last few months furthuring myself as a programmer and trying to re-learn the basics. There's still a huge amount of information I don't know about Python, however I know enough to make games, so that's what I'm doing.

Currently I'm working on Pong, and I'll update you guys on that whenever I ask a question on gamedev.

Now on to: Python List Comprehensions.

List comprehensions are a nice little tool in Python which add syntactic sugar. Like lambdas, they aren't needed however their existence makes programmers lives a little easier. Let's start by comparing traditional Python list syntax with List Comprehension Syntax:

Traditional Python:my_list = []for index in range(1,101): if index % 2 == 0: my_list.append(index ** 2)
List comprehension:my_list = [x**2 for x in range(1,101) if x % 2 == 0]
Just look at how much less space list comprehensions take up to do the same thing as a traditional for loop.

If you can't tell, the List Comprehension says that for every number in the range from 1-101, if x can be evenly divided by two then append x squared to my_list. Although you could accomplish this with a traditional python loop, the list comprehension is easier and just looks nicer.

What is the syntax?

my_list - empty list to store values from list comprehension in
for x in range(1,101) - values to check if statement against.
if x % 2 == 0 - If statement. All values from for statement are checked here.
x ** 2 - The value of this expression (it can be any expression) is appended to my_list when the if statement is true.

Let's look at a two dimensional example:

Traditional Python:my_list = []current_list = []for first in range(10): if y % 3 == 0: for second in range(first,first + 20,2): current_list.append(second) else: my_list.append(current_list) current_list = []
List Comprehension:my_list = [[x for x in range(y, y + 20, 2)] for y in range(10) if y % 3 == 0]
As you can see, it is a lot easier to use a list comprehension.

I hope that you now have a basic understanding of Python list comprehensions. They are a very useful tool :)!

Cheers :)!
Sign in to follow this  


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now