When I first saw a list comprehension I simply shook my head in utter confusion, the fact is that they are actually fairly straightforward, sure you can make them more and more complicated but here are some basic examples to get you started...
Take a look at the following, the first 'i' before the start of the for loop is referring to the variable 'i' within the for loop.
To turn the code into plain English to make it more clear: print i for each i in the range. Take a look at the code and it should make sense.
print [i for i in range(11)] ## output [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Lets look at this in a slightly different format...
myList = [i for i in range(11)] print myList ## output [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Here is more of a 'real world' example, something I actually used just the other day when I was doing a little web scraping and the data was returning empty strings into the list, so I did a list comprehension to simply make a new list with the empty strings removed.
myList = ['aaa', '', 'aba', 'bab', ''] newList = [i for i in filter(None, myList)] print newList ## output ['aaa', 'aba', 'bab']
To get the same output without using a list comprehension might look like this...
myList = ['aaa', '', 'aba', 'bab', ''] newList =  newList.append(filter(None, myList)) print newList ## output ['aaa', 'aba', 'bab']
So as you can see they are a little tidier and not that difficult to get started with. There's a nice tutorial with further examples found here.
Give Your Inbox Some Love
What You'll get?
- Posts like this delivered straight to your inbox!
- Nothing else.