SmithLogo

CSC 111

Introduction to Computer Science Through Programming

Smith Computer Science



Lecture Notes 17: Intro to Lists





List Intro

A list is a type of container in Python. These group objects together and have different properties.
Other containers are: tuples, dictionaries, and sets.

In a list, elements have a specific position (index) and allows access trhough the usual indexing operations... See it in use for string splitting:

Splitting and Joining Strings

Another typical task is to separate a string into a list of component substrings, or tokens.

You can try it here



split

The split method can achieve this by specifying the character(s) that are to be considered the separators between the tokens.

Example:
phrase = "time consumes everything but it is also the best"
tokens = phrase.split()
print("the phrase '{:s}' is composed of the tokens: {}".format(phrase, tokens))


Try it here

join

Another useful task is to join tokens into a longer string.

The format is:

< separator > . join ( < list of tokens > )

Example:

num_str = "1 2 3 4 5 6 7 8 9"
#making the tokens
tokens = num_str.split(" ")
print("the num_str '{:s}'\nis composed of the tokens:\n{}".format(num_str, tokens))
print()
# joining with '+'
num_expr = "+".join(tokens)
print("expression:",num_expr)
# you can use this for something!
print( eval(num_expr) )


Try it here



Different types!



Another useful property, is that the elements can have different types: integers, strings, floats and even other lists!!

We won't see this yet to avoid confusion, but the following is valid:

mixed_list = ["s", 42, True, "dog", 1.3, ['a', 'b', 'c']]

print(mixed_list)




A list structure

A list can be defined explicitly like this:
[ < list item at index 0 > , < list item at index 1 > , < ... > , < list item at index n-2 > , < list item at index n-1 > ]

Let's make and use a list in an example:

my_list = ["d", "a", "l", "l", "i", "a", "n", "c", "e"]
print(my_list)
print(my_list[7])
print(my_list[3:7])
print(my_list[1:])
print(my_list[1::2])
print ("".join(my_list))


Try it here



Lists are Mutable!

Lists, unlike strings, are mutable, which means that once created, the structure and or the values inside them can be change.

For example:

my_list = ["s", "c", "r", "e", "w"]
print (my_list)
my_list[1] = "h" # change an item
print(my_list)
length1 = len(my_list) 
# my_list[:length1]] all items after the last one
my_list[length1:] = "d" # append an item
print(my_list)
length2 = len(my_list)
del my_list[length2-2]
print(my_list)
my_list[2] = "o" # change an item
# my_list[:0]] all items up to but not including the first one
my_list[:0] = "snow"
print(my_list)


Try it here

Note that to append, the built-in function append(x) might be easier to use.

Side effects

Objects are complex structures saved in memory and handled through their named variables.

When we name an object, that name is like a handle that can be used to get into and use that object.

One thing that can happen, and that Python does often to optimize memory ussage, is to use different handles (variables) to point to the same value.



One big possible issue with this is that if we have two variables pointing at the same object, and the object is mutable, modifying the object trhough one variable, makes the change visible to the other.

Example:

my_teams = ['Raptors', 'Heat', 'Nets']
your_teams = my_teams  # both point to the same object now!
my_teams[1] = 'Lakers'  # Modify list element
print('My teams are:', my_teams)  # List element has changed
print('Your teams are:', your_teams)  # List element has changed too!


Try it here

Copying lists (or other mutable objects) can help here:

my_teams = ['Raptors', 'Heat', 'Nets']
your_teams = my_teams[:]  # Assign your_teams with a COPY of my_teams
my_teams[1] = 'Lakers'  # Modify list element
print('My teams are:', my_teams)  # List element has changed
print('Your teams are:', your_teams)  # List element has not changed


Try it here



When are there no side effects?

Assigning a variable with an element of an existing list, and then reassigning that variable with a different value does not change the list.

Example:
stooges = ['Larry', 'Shemp', 'Moe']
stooges[1] = 'Curly'  # Change list element
print(stooges)

fav_stooge = stooges[0]  # Bind to 'Larry'
fav_stooge = 'Iggy Pop'  # List not altered
print(stooges)


Try it here




List Methods

Lists, like Strings are objects. They have the internal values (references to other objects) as well as methods.

Here are some of the most useful ones:

Adding Elements

The following are different element addition variants:

Removing Elements

The following are different element removal variants:

Modifying Elements

The following are different "modifications":

Other Actions

The following are different element addition variants: Activity 1 [2 minutes]:
Open the Scratch pad and create a program that:
  1. create a list li with the contents: [1,3,5]
  2. print the list
  3. add the following list literal to the end of li: [2,4,6]
  4. print the list
  5. extract and save two elements so that you leave a list that is already sorted
  6. print the list
  7. Add the extracted elements in the correct location (index) in order to keep the list sorted
  8. print the list
  9. Add the following element to the list at index 3: -6
  10. print the list
  11. Figure out how to remove the element you just added. However, you are not allowed to use the commands list.remove(-6) nor list.pop(3)
  12. print the list


The result should look like this:






Homework (TBD)

[Due for everyone]


[Optional] TODO