In this lesson, you’ll see how operators and Python’s built-in functions can be applied to lists. Several Python operators can be used with lists. in
and not in
are membership operators and can be used with lists. A membership operator used on a list:
- Returns
True
if the first operand is contained within the second - Returns
False
otherwise - Can also be used as
not in
Here’s an example:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> 'spam' in a
True
>>> 'egg' in a
True
>>> 'kiwi' in a
False
>>> 'kiwi' not in a
True
Here’swhat happens with the concatenation (+
) and replication (*
) operators:
- The concatenation (
+
) operator concatenates the operands. - The replication (
*
) operator creates multiple concatenated copies.
Here’s an example:
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a + ['kiwi', 'mango']
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'kiwi', 'mango']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a * 2
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> 2 * a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster', 'spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
Several Python built-in functions can also be used with lists:
len()
returns the length of the list.min()
returns the object from the list with the smallest value.max()
returns the object from the list with the highest value.
Here’s an example:
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> len(a)
6
>>> b = [4, 99, 55, 23, 5, 6]
>>> b
[4, 99, 55, 23, 5, 6]
>>> len(b)
6
>>> min(b)
4
>>> max(b)
99
>>> min(a)
'bacon'
>>> max(a)
'tomato'
>>> c = ['apple', 'bacon', 'Asparagus', 'Zebra']
>>> c
['apple', 'bacon', 'Asparagus', 'Zebra']
>>> min(c)
'Asparagus'
>>> max(c)
'bacon'
>>> ord('A')
65
>>> ord('a')
97
>>> ord('z')
122
>>> ord('Z')
90
>>> max(c)
'bacon'
>>> d = [2, 3, 5, 8, 'apple', 'bacon', 'spam']
>>> len(d)
7
>>> min(d)
Traceback (most recent call last):
File "<input>", line 1, in <module>
min(d)
TypeError: '<' not supported between instances of 'str' and 'int'
mnemonic6502 on Feb. 5, 2020
This should be the learning template all video tutorials should adopt on this site, great job!