Python 3

home

Introduction to Python

davidbpython.com




Containers: More List Operations


using containers to collect data

Containers are Python objects that can contain other objects.







containers allow for manipulation and analysis

Once collected, values in a container can be sorted or filtered (i.e. selected) according to whatever rules we choose. A collection of integer or floating-point values offers many opportunities for analysis. We can calculate:


A collection of string values allows us to perform text analysis:






container object summary : list, set, tuple

Compare and contrast the characteristics of each container.


mylist =  ['a', 'b', 'c', 'd', 1, 2, 3]

mytuple = ('a', 'b', 'c', 'd', 1, 2, 3)

myset =   {'a', 'b', 'c', 'd', 1, 2, 3}

mydict =  {'a': 1, 'b': 2, 'c': 3, 'd': 4}

list: ordered, mutable sequence of objects tuple: ordered, immutable sequence of objects set: unordered, mutable, unique collection of objects dict: unordered, mutable collection of object key-value pairs, with unique keys (discussed upcoming)






review: the list container object

A list is an ordered sequence of values.


var = []                     # initialize an empty list

var2 = [1, 2, 3, 'a', 'b']   # initialize a list of values






review: subscripting a list

Subscripting allows us to read individual items from a list.


mylist = [1, 2, 3, 'a', 'b']       # list

xx = mylist[2]                     # 3

yy = mylist[-1]                    # 'b'






review: slicing a list

Slicing a list returns a new list.


var2 = [1, 2, 3, 'a', 'b']            # list

sublist1 = var2[0:3]                  # [1, 2, 3]

sublist2 = var2[2:4]                  # [3, 'a']

sublist3 = var2[3:]                   # ['a', 'b']

Remember the rules of slicing:






in operator: finding an item within a list

The in operator returns True if an item is in the list.


mylist = [1, 2, 3, 'a', 'b']             # list

if 'b' in mylist:                        # this is True for mylist
    print("'b' can be found in mylist")

print('b' in mylist)                     # True:  the 'in' operator
                                         # actually returns True or False

Ex. 5.1






summary functions: len(), sum(), max(), min()

Summary functions offer a speedy answer to basic analysis questions: how many? How much? Highest value? Lowest value?


mylist = [1, 3, 5, 7, 9]        # list

print(len(mylist))               # 5 (count of items)
print(sum(mylist))               # 25 (sum of values)
print(min(mylist))               # 1 (smallest value)
print(max(mylist))               # 9 (largest value)





sorting a list

sorted() returns a new list of sorted values.


mylist = [4, 9, 1.2, -5, 200, 20]

smyl = sorted(mylist)              # list, [-5, 1.2, 4, 9, 20, 200]

Ex. 5.2






concatenating two lists with +

List concatenation works in the same way as it does with strings.


var = ['a', 'b', 'c']
var2 = ['d', 'e', 'f']

var3 = var + var2            # list, ['a', 'b', 'c', 'd', 'e', 'f']





adding (appending) an item to a list

var = []

var.append(4)                # Note well! call is not assigned
var.append(5.5)              # list is changed in-place

print(var)                    # [4, 5.5]


5.11






the AttributeError exception

An AttributeError exception occurs when calling a method on an object type that doesn't support that method.


mylines = ['line1\n', 'line2\n', 'line3\n']

mylines = mylines.rstrip()         # AttributeError:
                                   # 'list' object has no attribute 'rstrip'

Debugging:


Understanding the name AttributeError:






the AttributeError when using .append()

This exception may sometimes result from a misuse of the append() method -- it should not be assigned to any variable.


mylist = ['a', 'b', 'c']

# oops:  returns None -- call to append() should not be assigned
mylist = mylist.append('d')

mylist = mylist.append('e')        # AttributeError:  'NoneType'
                                   # object has no attribute 'append'






the correct use of .append()

Just remember that we don't assign from .append().


mylist = ['a', 'b', 'c']

mylist.append('d')                 # now mylist equals ['a', 'b', 'c', 'd']






sidebar: removing a container item

There are a number of additional list methods to manipulate a list, though they are less often used.


mylist = ['a', 'hello', 5, 9]

popped = mylist.pop(0)      # str, 'a'
                            # (argument specifies the index  of the item to remove)

mylist.remove(5)            # remove an item by value
print(mylist)               # ['hello', 9]

mylist.insert(0, 10)
print(mylist)               # [10, 'hello', 9]




[pr]