Python lists
Contents
Python lists¶
Lists are like tuples, containers of many things, but they can be changed. Here is a list:
a = [1, 2, 3, 4, 5, 6, 7]
a
[1, 2, 3, 4, 5, 6, 7]
Notice that you define it with []
instead of ()
.
Just like tuples, you can get the length of the list with len
:
len(a)
7
And you can index lists in exactly the same way you index tuples:
a[0]
1
a[1]
2
a[2:5]
[3, 4, 5]
a[::2]
[1, 3, 5, 7]
a[::-2]
[7, 5, 3, 1]
You can also combine two lists into a new list, like this:
b = [3.1, 5.0, 2.]
c = a + b
c
[1, 2, 3, 4, 5, 6, 7, 3.1, 5.0, 2.0]
And here is the empty list:
[]
[]
type([])
list
len([])
0
a + []
[1, 2, 3, 4, 5, 6, 7]
So, lists behave just like tuples but with one main difference: You can change lists. For example, you can change the second element of the list to 3.4:
# before
a
[1, 2, 3, 4, 5, 6, 7]
a[1] = 3.4
# after
a
[1, 3.4, 3, 4, 5, 6, 7]
You can also put a new item at the end of the list using list.append()
.
Here is how:
# before
a
[1, 3.4, 3, 4, 5, 6, 7]
# Push the item at the end
a.append(6.3)
# after
a
[1, 3.4, 3, 4, 5, 6, 7, 6.3]
You can also remove the last item of the list using list.pop()
:
# before
a
[1, 3.4, 3, 4, 5, 6, 7, 6.3]
# remove the last item
a.pop()
6.3
Notice that the item was returned by pop()
.
Here is the list after the pop operation:
a
[1, 3.4, 3, 4, 5, 6, 7]
The last item was removed. Now append()
and pop()
are methods of the class list
. They can be accessed by doing a.append()
or a.pop()
.
We will talk about classes and methods in another hands-on activity.
You can access the methods of an object by typing the name of the object followed by a .
and then pressing the “tab” button of your keyboard.
Try it here:
a. # Get next to the dot and press "tab"
File "<ipython-input-22-47dc394261ae>", line 1
a. # Get next to the dot and press "tab"
^
SyntaxError: invalid syntax
Another way to get help about an object is to use help()
on it.
You can do:
help(a)
Help on list object:
class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
|
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
|
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
|
| The reverse flag can be set to sort in descending order.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None
This will give you essentially all the information about the object you need.
Now back to lists. We saw append()
and pop()
.
There are more built in methods.
insert()
is a useful one:
# before
a
[1, 3.4, 3, 4, 5, 6, 7]
a.insert(4, 23.5325)
a
[1, 3.4, 3, 4, 23.5325, 5, 6, 7]
Here is what it does:
help(a.insert)
Help on built-in function insert:
insert(index, object, /) method of builtins.list instance
Insert object before index.
remove()
is also useful:
# before
a
[1, 3.4, 3, 4, 23.5325, 5, 6, 7]
a.remove(3)
# after
a
[1, 3.4, 4, 23.5325, 5, 6, 7]
Here is what it does:
help(a.remove)
Help on built-in function remove:
remove(value, /) method of builtins.list instance
Remove first occurrence of value.
Raises ValueError if the value is not present.
Let’s try to remove something that is not there:
a.remove(0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-32-ae1fd24e9d23> in <module>
----> 1 a.remove(0)
ValueError: list.remove(x): x not in list
As I said before: Read the error messages!!!
The list.extend()
method allows you to append an entire list to a given list:
# before
a
[1, 3.4, 4, 23.5325, 5, 6, 7]
# extend
a.extend([0.3, 0.12, 123.])
# after
a
[1, 3.4, 4, 23.5325, 5, 6, 7, 0.3, 0.12, 123.0]
You can also sort a list like this:
# before
a
[1, 3.4, 4, 23.5325, 5, 6, 7, 0.3, 0.12, 123.0]
a.sort()
# after
a
[0.12, 0.3, 1, 3.4, 4, 5, 6, 7, 23.5325, 123.0]
Here is how you can count the occurence of a specific element in a list:
a.count(3.4)
1
a.count(0.0)
0
And here is how you can find the index of a list element:
idx = a.index(23.5325)
idx
8
a[idx]
23.5325
There more things you can do with lists, but that’s it for now.
Questions¶
Consider the list:
data = [23.0, 21.0, 23.0, 23.0, 23.84, 24.52]
Find how many occurances of 23.0 there are in
data
:
# Your code here
Find the mean of the
data
list, i.e., the sum of all elements divided by their number. Hint: Use the built-in python functionsum()
. Here is the help for sum:
help(sum)
The term iterable
above refers to either tuples or lists (it is more general, but we will explain it another time).
# your code here
Find the minimum and the maximum of
data
. Hint: Use the functionmin()
for the minimum.
# your code here
# your code here