List Methods

Lists are (Mutable) Objects

Lists are objects, and they have a slew of methods that you can call on them:

>>> s = 'hello'
>>> s.upper()
'HELLO'
>>> print(s)
hello
>>> numbers = [5, 3, 4]
>>> numbers.sort()
>>> print(numbers)
[3, 4, 5]

List Methods Continued

So…. why does this matter?

Some methods that you can call on lists

li = [1, 2, 3]

Adding Elements

Usage notes:

Removing Elements

Usage notes:

Miscellaneous Methods

Some Exercises

Make the First Element Last

Make the First Element Last Solution v1

def last_to_first(items):
	""" makes last element in list first, shifts every other element up one """
	if len(items) <= 1:
		return items
	else: 
		return [items[-1]] + items[0:-1]

assert [1] == last_to_first([1]), 'test that one element returns same list'
assert [] == last_to_first([]), 'test that empty list returns empty list'
assert [4, 1, 2, 3] == last_to_first([1, 2, 3, 4]), 'test that all elements shifted by one'

Make the First Element Last Solution v2

def last_to_first(items):
	""" makes last element in list first, shifts every other element up one """
	new_items = items[:]
	if len(items) > 1:
		new_items.insert(0, new_items.pop())
	return new_items


assert [1] == last_to_first([1]), 'test that one element returns same list'
assert [] == last_to_first([]), 'test that empty list returns empty list'
assert [4, 1, 2, 3] == last_to_first([1, 2, 3, 4]), 'test that all elements shifted by one'