Contents: 1. Lists 2. Slices 3. Dictionaries 4. Tuples
1. Lists
append()
The append() method adds the new list as a member of the old list.
+ Operator
Joins two lists together.
extend()
Same as the + operator but it is always cleaner to use a method call.
insert()
Add a member to a list at a certain index.
- Takes two parameters: the index and the item we want to insert at that index
del
Keyword for removing items from iterables or deleting whole variables.
remove()
Removes the first instance of the given object from a list.
del vs. remove():
- del removes items by index whereas the remove() method removes items by value
pop()
The deleted item is lost forever when using del or remove(), pop() allows us to save this removed item.
- The pop() method removes an item by index but gives us back the value
Task
Create a script that removes the vowels from words in a list and returns this new de-voweled list of words.
- You can see my solution here
2. Slices
[start:stop]
Both start and stop are optional and will cause the slice to start form the beginning or continue all the way to the end.
- We can combine list methods:
- Leaving the start or stop empty will instruct the slice to start at index 0 or stop at the end of the list
- We can make a copy of a list as below, useful for when you want to manipulate or change the list without losing its original state:
Steps
[start:stop:step]
- Steps change how python counts as it moves through the creation of a slice
- Positive steps, like 2, skip items from left to right by an index of 2
- Negative steps, like -1, move from right to left throughout the collection
- We’ll start with a simple list of 10 items:
- To get all of the even numbers from this list:
- To remove the 0, we start at index 2 which is the value 2:
- We can use slices with any iterable, e.g. to reverse a string:
- If we want the values between 2 and 8 in my_list but reversed:
- Here we start at index 9 and move through the list by -1 stopping at index 2, hence the start and stop positions being reversed; you cannot start at 2 and move back by -1 until you get to 9
Deleting Slices
Like lists, we use the del keyword for removing items from iterables but we can also combine slices with del.
- Lets start with a list of numbers and letters:
- To make this a list of letters only:
3. Dictionaries
Construction
A dictionary is a way to store data, just like a list, but instead of using only index numbers to get the data you can use almost anything. This lets you treat a dictionary like it’s a database for storing and organising data.
- Dictionaries contain a key and a value:
- We cannot access our keys like we would with a list:
- Instead we use the name of the key, in this case ‘name’ to access its value:
- We can have more than one key:
- Notice how the order of the keys change; this is why we cannot use indexes on dictionaries as the the order can change over time
Values
Values can be: lists, strings, booleans, dictionaries, objects, your own custom classes… they can be anything.
- Here the value is another dictionary with keys ‘first’ and ‘last’
- Again notice how the order of ‘last’ and ‘first’ change:
- We can access the values like so:
Keys
Keys can use: strings, numbers, booleans or tuples.
- This means you can use keys that are logical for whatever application you require
- For instance, if you are working on a 2-dimensional game requiring an x and y axis and you want to store what is in a given cell:
- Note: these keys are tuples which we will come to shortly
Managing Keys
This involves the deletion, adding and changing of keys in a dictionary.
- Let’s start with a simple dictionary:
- To delete the ‘job’ key we use:
- We can add new keys to the dictionary too:
- We can change the value of a key like so:
- If we wanted to change several keys at once we can use the update() method
- Using update() we can pass in a dictionary of keys and values to create or update a dictionary in a single step:
Unpacking Dictionaries
- We are used to using the format() method on strings using a blank placeholder {}:
- We can also give our placeholders a name:
- If we want this to be automated i.e. we don’t want to type these arguments out ourselves every time, we can use **:
- We are turning the key with the value that’s inside the dictionary into a key word equals a value inside of a function
Dictionary Iteration
Dictionaries, unlike strings and lists, do not have a set order but we can still loop over dictionaries because they are a collection just like strings and lists.
- First, lets create a dictionary:
- Now let’s create a for loop that loops over the another_dict dictionary, however here it only loops over the keys not the values:
- We can loop over the keys to print the values:
- We can also use the dictionary values() method to loop over the values:
- Using the values() method gives us the same data as the loop with the keys where we did the lookups but without having to do the lookups; using values() is slightly faster as it doesn’t have to access the dictionary multiple times
4. Tuples
Principles
- Tuples are immutable (cannot be changed)
- We make lists with [], dictionaries with {} and strings with “”
- Tuples are constructed with () or (more importantly) commas
Creating Tuples
Tuples are immutable (cannot be changed) and tuples are constructed with () or (more importantly) commas.
- Remember we make lists with [], dictionaries with {} and strings with “”
- We can create tuples like so:
Accessing Items
We can access items in a tuple the same way we do with lists.
Tuple Packing and Unpacking
This basically means assigning multiple variables at once. When we pack variables we’re putting multiple values into one variable. When we unpack variables we’re creating multiple variables from one piece of data.
- Here we will create a tuple that has two variables; a and b, and then we will set each of those variables to the corresponding value in this other tuple; (1, 2)
- This is simultaneous assignment
- Next we will unpack the tuple c into the variables d & e:
- We can make a new variable f have the same data as c by packing variables d & e into the variable f:
- We can swap variables through the power of tuples:
Tuples with Functions
If your function returns a tuple, you can have multiple variables on the left side of the equal sign and those values get split out.
- First we’ll create a simple function that returns the tuple (1, 2, 3):
- We can assign this tuple to a variable:
- We can also assign multiple variables to each value in the tuple returned by the function:
Enumerate
Enumerate is a useful function that takes an iterable, like a list, and returns a list of tuples where each tuple holds the index of the item and its value.
- First we’ll create a simple list, in this case a list of the alphabet:
- Now lets create a for loop that will print the index of the letter as well as the letter itself e.g. 1. a, 2. b, 3. c, etc:
- We can get the same result using step since step is a tuple and tuples have indexes; we can feed it into the string format() method:
- We can use * to automate this process without having to specify the variables in the format():
- Note: remember ** unpacks dictionaries