-
Lists
- Ordered sequence of information, accessible by index
- Denoted by [ ]
- A list contains elements usually homogenous, not commonly contain mixed types
- Elements can be changed -> mutable
- Changing elements
After the element is changed, it still points to the same object - Iterating over a list
for i in L:
total += i
List operation
- Add elements to end of list
L.append( )
Mutates the list
Everything in python is an object, lists are objects
Objects has functions and methods- Access this information by object_name.something()
Concatenate 2 lists
L1.extend( [0, 6] )
- Mutate with L.extend (some_list)
Remove
del ( L[index] ) #delete element at specific index
#removes element at end of list
#If no index is specified, removes the last element
#Or remove the element at the specified index
L.pop ( index)
#removes a specific element
#Removes the first occurrence if the element occurs multiple times
#Returns error if the element is not in the list
L.remove (element)
- Converts strings and back
#returns a list with every character from s in L
list(s)
# split a string on a character parameter
# if called without a parameter, splits on spaces
s.split( )
#turn a list of characters into a string
‘ ‘. join(L) (‘_’.join(L) - > “a_b_c” )
- reverse()
Mutation, Aliasing, Cloning
- Lists in memory
- Is an object in memory
- Variable name points to object
- Any variable pointing to that object is affected -> watch out the side effects
Aliases
append() has side effect
print is not ==
- If two lists print the same thing, does not mean they are the same structure
- Can test by mutating one and check
Cloning a list
Create a new list and copy every element
L2 = L1[:] #L2 is a copy of L1->different from L2 = L1
Sorting a list
Sort change the list, returns nothing
sorted() does not mutate list, must assign result to a variable
L.sort() changes L, sorted(L) gives a sorted version of L but L stays the same
Lists of lists of lists of…
Can have nested lists
Mutation and iteration
- Avoid mutating a list as you are iterating over it
for e in L1:
if e in L2: L1.remove( e)
L1 = [1,2,3,4] L2 = [1,4,2,6] -> L1 = [2,3,4]
When you remove 1 in L1, L1 changes and python will not see 2 in L1
Solution
Make a copy of L1 and iterate over L1_copy