Python Lists

Creating and accessing

myList = [4,2,8,6,1] # Create a list print( myList[0] ) # Display the first value (index 0) in the list myList[3] = 5 # Modify the 4th value (index 3)
  • A list is a sequence of values (a.k.a. items) which can be used like variables (similar to an array in Java).
  • To access the value in a list, you put the array name followed by the slot position containing the value, where 0 is the first slot.
  • If you pass a list as a function parameter value, changes made to the list within the function will remain changed out of the function.
  • A list can contain values of differing types, for example myList = [1,2,'apple','orange']

Copying and slicing

myList2 = myList[1:3] # Gets the values from index 1 up to (but not including) index 3 print( myList2 ) # This will display [2,8]
  • If you don't put a number before the ':', it will start at index 0.
  • If you don't put a number after the ':', it will get the values until the end of the List.
  • If you just leave a ':', it will copy all of the values.

Adding to a list

A = [1,2,3] B = [2,4,6] A.append( 9 ) # Adds a single value A.extend( [3,7] ) # Adds multiple values C = A + B # Combines lists into one
  • List A will become [1,2,3,9,3,7].
  • List C will be [1,2,3,9,3,7,2,4,6].

Removing values from a list

fruit = ["apple","orange","banana","pear","peach","grape"] fruit.remove("apple") # Remove by value del( fruit[0] ) # Deletes the first value from the list del( fruit[0:2] ) # Removes all values from index 0 up to (but not including 2) fruit.pop(1) # Removes the value at index 1
  • myList.pop(1) also gets the value that was removed, you can store it in a variable.
  • If no index is specified for pop(), it will remove last value by default.

Sorting

myList.sort() # Arrange values in order myList.reverse() # Reverse order of values myList2 = sorted( myList ) # Alternative sort
  • This will put them in numerical order for numbers (or abc order for text strings).

Other

length = len( myList ) # Gets the number of items in the list numFives = myList.count(5) # Count how many of specified value are contained in the list myIndex = myList.index(5) # Get index (position) of the first value 5 found in list myList.insert(2, "hi") # Adds "hi" to the list at index 2

Challenge

Make a list of 10 strings and a list of 5 strings, write code that modifies the first item and displays the last item. Run the code once for each list.

Completed