CIS 111 Lists

Objectives

  • Describe what a list is
  • Create lists in Python
  • Use Python lists
  • Access elements of a list
  • Access list documentation
  • Use a list comprehension

List overview

  • lists are an instance of the list class
  • to get list documentation: help(list)
  • a list is a mutable ordered sequence of values
  • lists are comma separated values surrounded by [ ] in Python
  • a list is a collection of items
  • items can be added and removed from a list (which makes the list mutable)
  • lists can be searched and sorted
  • a list is a sequence

List examples

help(list) # display documentation mylist = [] # create an empty list print(len(mylist)) # 0 mylist[0] = 'Hello' # IndexError (element does not exist) mylist.append("Hello"); # add to end of list print(len(mylist)) # 1 print(mylist) # ['Hello'] mylist.append(1968); # add three more items to list mylist.append("Kishwaukee"); mylist.append("College"); print(len(mylist)) # 4 print(mylist.__len__()) # 4 (access length as property of list object) print(mylist) # ['Hello', 1968, 'Kishwaukee', 'College'] mylist.insert(0, "CIS") # insert element at position 0 in list print(mylist) # ['CIS', 'Hello', 1968, 'Kishwaukee', 'College'] mylist.sort() # TypeError (can't compare number in list with strings) mylist.remove(1968) # removes 1968 from list mylist.sort() # sort list in place print(mylist) # ['CIS', 'College', 'Hello', 'Kishwaukee'] mylist.reverse() # reverse list in place print(mylist) # ['Kishwaukee', 'Hello', 'College', 'CIS'] print(mylist.index("Hello")) # 1 print(mylist.count("CIS")) # 3 mylist.append("College") # append another copy of 'College' print(mylist.count("College")) # 2 print(mylist) # ['Kishwaukee', 'Hello', 'College', 'CIS', 'College'] x = mylist.pop(3) # remove 'CIS' and store in x print(mylist) # ['Kishwaukee', 'Hello', 'College', 'College'] print(x) # CIS mylist[1] = "Bob" # change second element in list print(mylist) # ['Kishwaukee', 'Bob', 'College', 'College'] print(mylist[1]) # Bob for i in mylist: print(i) # newline separator for i in mylist: print(i, end=' ') # space separator del mylist[1] # removes second item from list print(mylist) # ['Kishwaukee', 'College', 'College'] # List comprehension examples list1 = [1, 5, 12, 6] [item * 2 for item in list1] # [2, 10, 24, 12] [item**2 for item in list1] # [1, 25, 144, 36] [item**2 for item in list1 if item % 2 != 0] # [1, 25]