List methods and operations

List methods and operationsΒΆ

Methods and operations can also be used to build statements.

In the Python documentation you will find several methods and operations that are commands to modify lists. They are documented in mutable sequences.

Here we show some of the most common ones. Remeber that statements do not have values, they do something (like assignment: change the value of a variable).

lst = [1,2,3,4]
lst
[1, 2, 3, 4]
lst.reverse()
lst
[4, 3, 2, 1]
lst.sort()
lst
[1, 2, 3, 4]
import random
random.shuffle(lst)
lst
[3, 2, 4, 1]
# Be careful of this kind of thing:

s = lst.sort()
# commands do not have values! So what did we store in s?

s
# what type does s have?

type(s)
NoneType
random.shuffle(lst)
# Can Python calculate a sorted version of a list?
# YES! We know this from the chapter on expressions, 
# Python has the function sorted that given a list calculates 
# another list that is a sorted version of the argument!

s = sorted(lst)
(lst, s)
([3, 1, 4, 2], [1, 2, 3, 4])
# Assign to a slice

s[1:3]=[0,0]
s
[1, 0, 0, 4]
# Assign to a slice!

s[1:3] = []
s
[1, 4]
# repeat s 

s *= 3
s
[1, 4, 1, 4, 1, 4]