• 08/16/13 07:41 PM
    Sign in to follow this  

    Advanced Python Part One: List Comprehensions

    General and Gameplay Programming

    This is an extension of my blog article about list comprehensions and the first part of an advanced python series. We will cover List Comprehensions, Lambdas, Functional Programming, Map / Reduce / Filter, Decorators, and Descriptors.

    Python List Comprehensions

    List comprehensions are Python's solution to the large loops required to do tasks which should be easy. They transform the simple task of getting all the even numbers between zero and one-thousand from: [code] my_list = [] for index in range(1000): if index % 2 == 0: my_list.append(index) [/code] to [code] my_list = [x for x in range(1000) if x % 2 == 0] [/code]

    The use for list comprehensions

    List comprehensions are essentially: [code] list_name = [expression values filter] [/code] Values - A [tt]for[/tt] loop of values to check against the filter Filter - All values go through this. It is an [tt]if[/tt] statement, and the expression is appended to the end of the list when it is true. Expression - Data to append onto the list if Filter is true It's important to note here that the expression could be anything. We could get the squares of all even numbers between zero and one-thousand just as easily: [code] my_list = [x**2 for x in range(1000) if x % 2 == 0] [/code]

    Interesting Points

    List comprehensions work on strings, and the [tt]for[/tt] loop can loop through any list. The expression can be as complex as you want. The expression is what gets appended, and it can even be another list. Look at this piece of code: [code] my_list = [[x*y for y in range(1,11) if y % 2 == 0] for x in range(1,11) if x % 2 == 0] [/code] This generates a list of lists (which is stored in [tt]my_list[/tt]) where every even number between one and ten is multiplied by every other even number between one and ten.


    To practice list comprehensions you can try out Code Academy's interactive course. You can also learn more by looking at the Python Docs List Comprehensions are a very useful tool which can replace many loops if you look out for it. Cheers :)!

    Article Update Log

    [b]June 20 2013[/b] - Released Article [b]August 19 2013[/b] - Added in Python Docs Link.

      Report Article
    Sign in to follow this  

    User Feedback

    Create an account or sign in to leave a review

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

    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


    Report ·


    Share this review

    Link to review

    Report ·


    Share this review

    Link to review