PYTHON LISTS AND DICTIONARIES

Introduction to Lists

Lists are a datatype you can use to store a collection of different pieces of information as a sequence under a single variable name. (Datatypes you’ve already learned about include strings, numbers, and booleans.)
You can assign items to a list with an expression of the form
list_name = [item_1, item_2]
with the items in between brackets. A list can also be empty: empty_list = [].
Lists are very similar to strings, but there are a few key differences.

Access by Index

You can access an individual item on the list by its index. An index is like an address that identifies the item’s place in the list. The index appears directly after the list name, in between brackets, like this: list_name[index].
List indices begin with 0, not 1! You access the first item in a list like this: list_name[0]. The second item in a list is at index 1: list_name[1]. Computer scientists love to start counting from zero.

Late Arrivals & List Length

A list doesn’t have to have a fixed length. You can add items to the end of a list any time you like!
letters = ['a', 'b', 'c'] letters.append('d') print len(letters) print letters
  1. In the above example, we first create a list called letters.
  2. Then, we add the string 'd' to the end of the letters list.
  3. Next, we print out 4, the length of the letters list.
  4. Finally, we print out ['a', 'b', 'c', 'd'].

  1. List Slicing

  1. Sometimes, you only want to access a portion of a list. Consider the following code:
    letters = ['a', 'b', 'c', 'd', 'e'] slice = letters[1:3] print slice print letters
    What is this code doing?
    First, we create a list called letters.
    Then, we take a subsection of the list and store it in the slice list. We do this by defining the indices we want to include after the name of the list: letters[1:3]. In Python, when we specify a portion of a list in this manner, we include the element with the first index, 1, but we exclude the element with the second index, 3.
    Next, we print out slice, which will print ['b','c']. Remember, in Python indices always start at 0, so the 1 element is actually b.
    Finally, we print out ['a', 'b', 'c', 'd', 'e'], notice that we did not modify the original letters list.
  2. Slicing Lists and Strings

    You can slice a string exactly like a list! In fact, you can think of strings as lists of characters: each character is a sequential item in the list, starting from index 0.
    my_list[:2] # Grabs the first two items my_list[3:] # Grabs the fourth through last items
    If your list slice includes the very first or last item in a list (or a string), the index for that item doesn’t have to be included.
  3. Maintaining Order

    Sometimes you need to search for an item in a list.
    Pets = ["Cow", "Dog", "Cat"] print Pets.index("Dog")
    1. First, we create a list called Pets with three strings.
    2. Then, we print the first index that contains the string "Dog", which will print 1.
    We can also insert items into a list.
    Pets.insert(1, "") print Pets
    1. We insert "dog" at index 1, which moves everything down by 1.
    2. We print out ["ant", "dog", "bat", "cat"]

    For One and All

    If you want to do something with every item on the list, you can use a for loop. If you’ve learned about for loops in JavaScript, pay close attention! They’re different in Python.
    for variable in list_name: # Your stuff!
    A variable name follows the for keyword; it will be assigned the value of each list item in turn.
    Then in list_name designates list_name as the list, the loop will work on. The line ends with a colon (:) and the indented code that follows it will be executed once per item in the list.
  4. More with 'for'

    If your list is a jumbled mess, you may need to sort() it.
    Pets = ["Cow", "Dog", "Cat"] Pets.sort() for animal in Pets: print(animal)
    1. First, we create a list called  animals  with three strings. The strings are not in alphabetical order.
    2. Then, we sort  animals into alphabetical order. Note that .sort() modifies the list rather than returning a new list.
    3. Then, for each item in animals, we print that item out as "Cow", "Dog", "cat" on their own line each.
    4. New Entries

      Like Lists, Dictionaries are mutable. This means they can be changed after they are created. One advantage of this is that we can add new key/value pairs to the dictionary after it is created like so:
      dict_name[new_key] = new_value
      An empty pair of curly braces {} is an empty dictionary, just like an empty pair of [] is an empty list.
      The length len() of a dictionary is the number of key-value pairs it has. Each pair counts only once, even if the value is a list. (That’s right: you can put lists inside dictionaries!)
    5. Changing Your Mind

      Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with the del command:
      del dict_name[key_name]
      will remove the key key_name and its associated value from the dictionary.
      A new value can be associated with a key by assigning a value to the key, like so:
      dict_name[key] = new_value
    6. Remove a Few Things

      Sometimes you need to remove something from a list.
      beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatles
      This code will print:
      ["john","paul","george","ringo"]
      1. We create a list called beatles with 5 strings.
      2. Then, we remove the first item from beatles that matches the string "stuart". Note that .remove(item) does not return anything.
      3. Finally, we print out that list just to see that "stuart" was actually removed.

      Lists + Functions

      Functions can also take lists as inputs and perform various operations on those lists.
      def count_small(numbers): total = 0 for n in numbers: if n < 10: total = total + 1 return total lotto = [4, 8, 15, 16, 23, 42] small = count_small(lotto) print small
      1. In the above example, we define a function count_small that has one parameter, numbers.
      2. We initialize a variable total that we can use in the for loop.
      3. For each item n in numbers, if n is less than 10, we increment total.
      4. After the for loop, we return total.
      5. After the function definition, we create an array of numbers called lotto.
      6. We call the count_small function, pass in lotto, and store the returned result in small.
      7. Finally, we print out the returned result, which is 2 since only 4 and 8 are less than 10.

No comments:

Powered by Blogger.