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 numeric values offers many new opportunities for analysis:


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





container objects: 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}






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']       # initialize a list of values

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']            # initialize a list of values

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

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

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

Remember the rules of slicing, similar to strings:





finding an item within a list

The 'in' operator works with lists similar to how it works with strings.


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

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




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]        # initialize a 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)                     # [-5, 1.2, 4, 9, 20, 200]




concatenating two lists with +

Concatenation works in the same way as strings.


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

var3 = var + var2                  # ['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]

It is the nature of a list to hold these items in order as they were added.





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'





the AttributeError when using .append()

This exception may sometimes result from a misuse of the append() method, which returns None.


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'





avoiding the incorrect use of .append()

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

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





sidebar: removing a container element

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 element by value

print(mylist)               # ['hello', 9]

mylist.insert(0, 10)

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




[pr]