fabsta
8/28/2016 - 8:25 PM

6. lists (python).md

LISTS

properties: ordered, iterable, mutable, can contain multiple data types

create an empty list (two ways)

empty_list = []
empty_list = list()

create a list

simpsons = ['homer', 'marge', 'bart']

examine a list

simpsons[0]     # print element 0 ('homer')
len(simpsons)   # returns the length (3)

modify a list (does not return the list)

simpsons.append('lisa')                 # append element to end
simpsons.extend(['itchy', 'scratchy'])  # append multiple elements to end
simpsons.insert(0, 'maggie')            # insert element at index 0 (shifts everything right)
simpsons.remove('bart')                 # searches for first instance and removes it
simpsons.pop(0)                         # removes element 0 and returns it
del simpsons[0]                         # removes element 0 (does not return it)
simpsons[0] = 'krusty'                  # replace element 0

concatenate lists (slower than 'extend' method)

neighbors = simpsons + ['ned','rod','todd']

find elements in a list

simpsons.count('lisa')      # counts the number of instances
simpsons.index('itchy')     # returns index of first instance

list slicing [start:end:stride]

weekdays = ['mon','tues','wed','thurs','fri']
weekdays[0]         # element 0
weekdays[0:3]       # elements 0, 1, 2
weekdays[:3]        # elements 0, 1, 2
weekdays[3:]        # elements 3, 4
weekdays[-1]        # last element (element 4)
weekdays[::2]       # every 2nd element (0, 2, 4)
weekdays[::-1]      # backwards (4, 3, 2, 1, 0)

alternative method for returning the list backwards

list(reversed(weekdays))

sort a list in place (modifies but does not return the list)

simpsons.sort()
simpsons.sort(reverse=True)     # sort in reverse
simpsons.sort(key=len)          # sort by a key

return a sorted list (but does not modify the original list)

sorted(simpsons)
sorted(simpsons, reverse=True)
sorted(simpsons, key=len)

insert into an already sorted list, and keep it sorted

num = [10, 20, 40, 50]
from bisect import insort
insort(num, 30)

create a second reference to the same list

same_num = num
same_num[0] = 0         # modifies both 'num' and 'same_num'

copy a list (two ways)

new_num = num[:]
new_num = list(num)

examine objects

id(num) == id(same_num) # returns True
id(num) == id(new_num)  # returns False
num is same_num         # returns True
num is new_num          # returns False
num == same_num         # returns True
num == new_num          # returns True (their contents are equivalent)

Selecting Items In A List With Filters

regimentSize = (5345, 6436, 3453, 2352, 5212, 6232, 2124, 3425, 1200, 1000, 1211); 

smallRegiments = list(filter((lambda x: x < 2500), regimentSize));

Flatten Lists Of Lists

Create a list containing three lists of names

list_of_lists = [['Amy','Betty','Cathryn','Dana'], 
                 ['Elizabeth','Fay','Gora'], 
                  ['Heidi','Jane','Kayley']]

For each element in list_of_lists, take each element in the list

flattened_list = [i for row in list_of_lists for i in row]

equivalent list comprehension

items = [item for row in matrix
              for item in row]      # [1, 2, 3, 4]

Create a list of first names

first_names = ['Steve', 'Jane', 'Sara', 'Mary','Jack','Bob', 'Bily', 'Boni', 'Chris','Sori', 'Will', 'Won','Li']

Create a function called "chunks" with two arguments, l and n:

def chunks(l, n):
    # For item i in a range that is a length of l,
    for i in range(0, len(l), n):
        # Create an index range for l of n items:
        yield l[i:i+n]

Create a list that from the results of the function chunks:

list(chunks(first_names, 5))
[['Steve', 'Jane', 'Sara', 'Mary', 'Jack'],
 ['Bob', 'Bily', 'Boni', 'Chris', 'Sori'],
 ['Will', 'Won', 'Li']]