YouTube

Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← 02-24 List Comprehensions

Get Embed Code
1 Language

Showing Revision 1 created 04/23/2012 by Amara Bot.

  1. [Norvig] And before I do generator expressions, we're going to do list comprehensions.
  2. You've seen them before.
  3. We saw in Unit 1 we said that we could get the list of suits by saying
  4. [s for r, s in cards].
  5. And so the format here is we have the individual term of the list comprehension
  6. and here we have a for clause.
  7. And in general, we're going to have 1 for clause at least
  8. and then, optionally, we could have more here, either for or if clauses.
  9. And that's what a list comprehension looks like in general.
  10. Now, what does the list comprehension mean?
  11. This expression is similar to saying we're going to write out a loop where we say
  12. the result starts as the empty list,
  13. then we take the for part and then we take the term and append that into the result.
  14. And then when we're all done, result will hold the value of this expression.
  15. Now I'm going to show you a more complex list comprehension.
  16. Say we wanted the list of suits for all our face cards.
  17. Then we could say s for r, s in cards if the rank of the cards is, say,
  18. in jack, queen, king.
  19. I don't know why you'd want that, but there's a possibility.
  20. So I've got the term I'm building up, I've got 1 for loop controlling it,
  21. and now I've got an if statement, and that's as if we had written this code
  22. if we had inserted inside the for loop an if statement
  23. and then only done the appending of the term s if the if statement is true.
  24. And in general, we can have any number of for statements, if statements,
  25. more for statements, more if statements.
  26. We can keep on adding those for clauses and if clauses
  27. and intermingling them in any order we want,
  28. as long as the for clause comes first.
  29. And we can have that 1 big list comprehension, and that corresponds to
  30. putting in more fors and ifs here in this loop.
  31. The whole thing is read left to right except for the term.
  32. So the way to read a list comprehension is to say
  33. I'm going to ignore the first part for now,
  34. and then I think of it as saying it's a bunch of nested statements--
  35. for statements, if statements, for statements.
  36. They all get nested deeper and deeper.
  37. Then when I get to the end, the very last clause, now I'm appending together the term,
  38. so now read the term.
  39. And that's why it's okay that term here looks like it's referencing a variable s
  40. that hasn't been defined yet.
  41. That's okay because s has been defined here.
  42. And it looks like it's used before it's defined, but that's not the case,
  43. because when it's actually used is right down here at the end.