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
- In the above example, we first create a list called
letters
. - Then, we add the string
'd'
to the end of theletters
list. - Next, we print out
4
, the length of theletters
list. - Finally, we print out
['a', 'b', 'c', 'd']
.
- List Slicing
- 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 lettersWhat is this code doing?First, we create a list called
letters
.Then, we take a subsection of the list and store it in theslice
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 outslice
, which will print['b','c']
. Remember, in Python indices always start at0
, so the1
element is actuallyb
.Finally, we print out['a', 'b', 'c', 'd', 'e']
, notice that we did not modify the originalletters
list. 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 itemsIf 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.Maintaining Order
Sometimes you need to search for an item in a list.Pets = ["Cow", "Dog", "Cat"] print Pets.index("Dog")- First, we create a list called
Pets
with three strings. - Then, we print the first index that contains the string
"Dog"
, which will print1
.
We can alsoinsert
items into a list.Pets.insert(1, "") print Pets- We insert
"dog"
at index 1, which moves everything down by 1. - 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 afor
loop. If you’ve learned aboutfor
loops in JavaScript, pay close attention! They’re different in Python.for variable in list_name: # Your stuff!A variable name follows thefor
keyword; it will be assigned the value of each list item in turn.Thenin list_name
designateslist_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.- First, we create a list called
More with 'for'
If your list is a jumbled mess, you may need tosort()
it.Pets = ["Cow", "Dog", "Cat"] Pets.sort() for animal in Pets: print(animal)- First, we create a list called
animals
with three strings. The strings are not in alphabetical order. - Then, we sort
animals
into alphabetical order. Note that.sort()
modifies the list rather than returning a new list. - Then, for each item in
animals
, we print that item out as"Cow", "Dog", "cat"
on their own line each. 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_valueAn empty pair of curly braces{}
is an empty dictionary, just like an empty pair of[]
is an empty list.The lengthlen()
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!)Changing Your Mind
Because dictionaries are mutable, they can be changed in many ways. Items can be removed from a dictionary with thedel
command:del dict_name[key_name]will remove the keykey_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_valueRemove a Few Things
Sometimes you need to remove something from a list.beatles = ["john","paul","george","ringo","stuart"] beatles.remove("stuart") print beatlesThis code will print:["john","paul","george","ringo"]- We create a list called
beatles
with 5 strings. - Then, we remove the first item from
beatles
that matches the string"stuart"
. Note that.remove(item)
does not return anything. - 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- In the above example, we define a function
count_small
that has one parameter,numbers
. - We initialize a variable
total
that we can use in thefor
loop. - For each item
n
innumbers
, ifn
is less than 10, we incrementtotal
. - After the
for
loop, we returntotal
. - After the function definition, we create an array of numbers called
lotto
. - We call the
count_small
function, pass inlotto
, and store the returned result insmall
. - Finally, we print out the returned result, which is
2
since only4
and8
are less than 10.
- We create a list called
- First, we create a list called
No comments: