Wednesday, January 16, 2013

What I learned: List Comprehensions.

The most interesting thing I learned last week was using list comprehensions in Python.

During last week's Wednesday's lecture, when talking about certain boolean functions, the professor rewrote those boolean functions using list comprehensions.

For example the piece of code:

for x in L1 :
    if x in L2 : return False
return True

Can be rewritten with list comprehensions as:

return False in [x in L2 for x in L1]

In my opinion the second piece of code is more clearer and concise than the first piece of code. I wish I knew about list comprehensions when I took CSC148 last semester, as it seems like a much easier and clearer way of manipulating and using lists.

 




4 comments:

  1. It's great that you find list comprehension easy! Most people find it hard to understand and to use when they first learn about it.

    Don't forget though that this is a theoretical computer science course and thus you should focus on the relevant material.

    ReplyDelete
    Replies
    1. Thank you, I will keep that in mind for future posts.

      Delete
  2. Double-check the list comprehension and original code. See whether they actually produce the same result.

    ReplyDelete
  3. I had a lot of trouble with this too! Great post!

    ReplyDelete