Other List Operations
Most important list operations covered during this video:
in
len
count
The in
operator
Checking if a given element is part of a list is a simple operation that will involve the in
operator. Let's see an example first:
shopping_list = ['Milk', 'Eggs', 'Bread']
print('Bread' in shopping_list) # True
print('Cookies' in shopping_list) # False
do_i_need_to_buy_milk = 'Milk' in shopping_list
print(do_i_need_to_buy_milk) # True
Something to note is that in
is an operator, not a function (as len
, for example) or a list method (like my_list.remove()
or my_list.append()
). We use in
as we'd use other operators (+
, -
, etc).
The len
operator
Given a list my_list
, how can you know how many elements does it have? The answer is simple: the len
function:
my_list = ['a', 'b', 'c']
print(len(my_list)) # 3
my_list.append('d')
new_length = len(my_list)
print(new_length) # 4
We usually refer to "counting elements" as "getting the length of a list". You can associate the len
function with the length word.
Files associated with this lesson:
Other Operations with Lists.ipynb
Other Operations with Lists¶
Membership¶
shopping_list = ['Milk', 'Eggs', 'Bread']
'Milk' in shopping_list
'Apples' in shopping_list
Searching elements¶
shopping_list.index('Milk')
shopping_list.index('Eggs')
shopping_list.index('Apples')
Min & Max¶
l1 = [19, 3, 81, 17, 99]
l2 = ['h', 'e', 'l', 'l', 'o']
min(l1), max(l1)
min(l2), max(l2)
Sorting Elements¶
Mutable solution, using lists' sort()
method
shopping_list = ['Milk', 'Eggs', 'Bread']
shopping_list.sort()
print(shopping_list)
Immutable solution, using sorted()
builtin function
shopping_list = ['Milk', 'Eggs', 'Bread']
sorted_list = sorted(shopping_list)
print(sorted_list)
print(shopping_list) # not changed
More operations for you to explore:¶
- Counting elements:
count()
. More advanced, using theitertools module
. - Reversing a list:
reverse
or indexing (future lesson). - Copying a list:
copy
or indexing (future lesson).