Python Lists

CSCI 1913 – Introduction to Algorithms, Data Structures, and Program Development
Adriana Picoral

Thinking and planning

  • Planning and typing are separate
    • Plan first (this is the hard part!)
    • Translate the plan into language of your choice
  • Hard to read code is rarely necessary and always bad
    • If your peers can’t read it, it doesn’t matter if it works
    • Code is Communication. prepare it and proofread it just like an essay
  • Multiple solutions to every problem. Pick the best one

Lists

Lists are similar to tuples, with one important difference: lists are mutable

Lists and tuples:

  • store ordered items that can repeat
  • can be indexed
  • we can use built-in functions like len(), max(), min()

Lists

Use square brackets to create a list (not optional like tuples).

my_list = ["Peter", 10, 10.0, "apple"]
print(my_list[0])
Peter

Can also use the list() constructor:

empty_list = []
another_empty_list = list()

Lists

Lists are mutable, so we can modify a value using its index

my_list = ["Peter", 10, 10.0, "apple"]
print(my_list[0])
Peter
my_list[0] = "Mary"
print(my_list)
['Mary', 10, 10.0, 'apple']

While we can index a tuple, we cannot modify items in a tuple

Lists

Lists are mutable, so we can modify lists with methods:

  • .append(item) adds an item to the end of the list
  • .insert(index, item) adds an item to index position (rest of list shifts right)
  • .remove(item) removes the first matching item
  • .pop(index) removes item at index (returns the removed value)

Keyword: in

  • The keyword in determines whether an element is in a collection, returns True or False
"nas" in "Bananas"

Exercise

Write a python function that given a string, it returns two lists: one with all vowels (a, e, i, o, u) and another with all consonants.

Test cases:

if __name__ == "__main__":
    assert vowels_consonants("") == ([], [])
    assert vowels_consonants("aeaAR") == (["a", "e", "a", "A"], ["R"])
    assert vowels_consonants("abcd") == (["a"], ["b", "c", "d"])

    print("Passed all tests")

Submit your vowels_consonants.py file to gradescope.