Lists



Overview



Lists are dynamic i.e. they can grow and shrink
• Lists can “Contain”
◇ Any python objects
◇ Another list

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Defind a List



# Define a list
books_to_read = ["Cryptonomicon""Mediations""The Prophet"]

# Instructions can be modeled as a list
# (lists gurantee order)
intructions = [ "Buy Deus Ex (1999)",
    "Insert Disk into your computer",
    "Install the game",
    "Play the first level (Liberty Island)",
    "Call out sick from work",
    "Order pizza",
    "Close the curtains and turn off the lights",
]


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

List Indexes & How indexes work



• Access elements in the list via indexes
• Indexes start at 0
• Positive and Negative indexes
First element index = 0; Last element index = -1

# List Indexes

# Start counting at 0
#  0      1       2        3
["one""two""three""four"]     # from the beginning
# -4     -3      -2       -1        # from the end


# Access List element
>>> l = ['a'118.2]
>>> l[2]
18.2

# First element
>>> ["one""two""three""four"][0]
'one'

# Last element
>>> ["one""two""three""four"][-1]
'four'


# Change List element
>>> l[2] = 20.4
>>> l
['a'120.4]


# You can access an element and then do stuff to that object immediately
print("I want to " + Instructions[5].lower())


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

List Properties



# Length
len(books_to_read)
len("Hello World")          # strings are a collection of characters



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

List Methods



• Use .append() method to append item to end of list

# Grow the list
instructions.append("You're welcome")   # add one item at a time
instructions.extend(['hi''there'])    # multiple items (recommend)

# Legal, but not recommended
instructions += ['hi''there']         # multiple items


# Replace an elment
instructions[-1] = "This replaces the last element"
instructions[0] = "This replaces the 0th element"


# Insert an element
instructions.insert(0"First, calm theyself.")


# Delete by index - last two elements ([-1] and [-2])
del instructions[-1]
print (instructions)
del instructions[-1]    # was second to last, now last
print(instructions)


# Remove elements by VALUE
instructions.remove('removeme')     # only delete first occurrence


# Pop (removes the last (-1th) element AND returns a List Element)
instructions.pop()
some_value = instructions.pop()
print some_value

# Pop a different index
fourth = instructions.pop(3)


# Sorting
sorted(instructions)    # new, temp, sorted list
instructions.sort()     # modify the 'instructios'


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Other list methods



https://docs.python.org/3/tutorial/datastructures.html#more-on-lists

Index