English subtitles

← List Operations - Intro to Computer Science

Get Embed Code
6 Languages

Showing Revision 6 created 05/24/2016 by Udacity Robot.

  1. [Narrator] I hope you're getting a sense that lists are very powerful.
  2. That by using mutation, by having lists that could contain other lists
  3. or any other kind of data we want,
  4. we can build very complex data structures, and we can do lots of interesting things.
  5. I'm going to introduce 1 more list operation,
  6. which will allow us to add a new element at the end of the list.
  7. We've seen that we can use lists to store complex data,
  8. that elements of the list can be any type we want including other lists,
  9. and we've seen that we can use mutation to change the value of a list,
  10. and that mutation is visible through any reference to the same list object.
  11. Now I'm going to introduce some other list operations.
  12. The first one is append, and append is like a procedure but it's a method,
  13. so we use it similar to the way we use to find on strings.
  14. We'll have a list first, then a dot followed by append,
  15. and what we pass in is the element we want to append to the list.
  16. Append will add a new element to the end of a list,
  17. and the important thing about append is that it's mutating
  18. the list that its invoked on.
  19. It's not creating a new list; it's mutating the old list.
  20. As an example of the use of append let's assume that instead of
  21. replacing curly in the 3 stooges, we want to end up with 4 stooges.
  22. We'll add Shemp and add the other 3 as they are.
  23. So what we want to do is to append Shemp at the end of the list we have.
  24. We would do that by invoking append on the stooges,
  25. passing in the string Shemp as the input.
  26. Here's what happens after the first assignment,
  27. the name stooges refers to the list containing the 3 elements,
  28. Moe, Larry, and Curly.
  29. When we invoke append it modifies that object,
  30. adding a new element to it.
  31. After the append, the list that stooges refers to now has 4 elements.
  32. We have not created a new list.
  33. Note that there's no assignment from the result of append.
  34. What we've done is modify the value that stooges refers to
  35. by adding a new element to it.