Overview

Teaching: 15 min
Exercises: 10 min
Questions
  • How can I store multiple values?

Objectives
  • Explain why programs need collections of values.

  • Write programs that create flat lists, index them, slice them, and modify them through assignment and method calls.

A list stores many values in a single structure.

roi_volumes = [2.73,145.3,12.7,16.2, 27.6]
# Volume of ROIs :  
roi_volumes
[2.73,145.3,12.7,16.2, 27.6]
# length: 
len(roi_volumes)
5

Use an item’s index to fetch it from a list.

# The item with index 0 in the list is : 
roi_volumes[0]
2.73
# The item with index 4 in the list is : 
roi_volumes[4]
27.6

Lists’ values can be replaced by assigning to them.

roi_volumes[0] = 26.5
# Our list is now: 
roi_volumes
Our list is now: [26.5,145.3,12.7,16.2, 27.6]

Appending items to a list lengthens it.

# Our list is initially: 
roi_volumes 
[26.5,145.3,12.7,16.2, 27.6]
roi_volumes.append(14.2)
roi_volumes.append(140)
# Our list has now become: 
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2,140]

Use del to remove items from a list entirely.

# roi_volumes before removing last item: 
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2,140]
del roi_volumes[6]
# roi_volumes after removing last item: 
roi_volumes
[26.5,145.3,12.7,16.2, 27.6,14.2]

The empty list contains no values.

Lists may contain values of different types.

goals = [1, 'Create lists.', 2, 'Extract items from lists.', 3, 'Modify lists.']

While this list can be created there are better ways of representing this type of information.

Character strings can be indexed like lists.

label_for_roi = 'cortex_left'
# The character indexed by 0: 
label_for_roi[0]
# The character indexed by 3: 
c
label_for_roi[3]

t

Character strings are immutable.

label_for_roi[0] = 'C'
TypeError: 'str' object does not support item assignment

Indexing beyond the end of the collection is an error.

# The character indexed by 99 is: 
label_for_roi[99]
IndexError: string index out of range

Fill in the Blanks

Fill in the blanks so that the program below produces the output shown.

values = []
values.____(1)
values.____(3)
values.____(5)
print('first time:', values)
values = values[____]
print('second time:', values)
first time: [1, 3, 5]
second time: [3, 5]

Solution

values = []
values.append(1)
values.append(3)
values.append(5)
print('first time:', values)
values = values[1:3]
print('second time:', values)

How Large is a Slice?

If ‘low’ and ‘high’ are both non-negative integers, how long is the list values[low:high]?

Solution

high-low

From Strings to Lists and Back

Given this:

print('string to list:', list('ADHD'))
print('list to string:', ''.join(['c', 'n', 's']))
string to list: ['A', 'D', 'H', 'D']
list to string: 'cns'
  1. Explain in simple terms what list('some string') does.
  2. What does '-'.join(['x', 'y']) generate?

Working With the End

What does the following program print?

roi_label = 'hippocampus'
print(roi_label[-1])
  1. How does Python interpret a negative index?
  2. If a list or string has N elements, what is the most negative index that can safely be used with it, and what location does that index represent?
  3. If values is a list, what does del values[-1] do?
  4. How can you display all elements but the last one without changing values? (Hint: you will need to combine slicing and negative indexing.)

Solution

1: It retrieves elements by stepping backwards through the string.
2: -N. This location is the first element in the list.
3: It deletes the last element in the list.
4: values[0:-1]

Stepping Through a List

What does the following program print?

roi_label = 'hippocampus'
print(roi_label[::2])
print(roi_label[::-1])
  1. If we write a slice as low:high:stride, what does stride do?
  2. What expression would select every other element, starting from the second?

Solution

hpoaps
supmacoppih

1: stride is the step to go through the list

The answer to question 2 is:

listobject[1::2]

Slice Bounds

What does the following program print?

roi_label = 'hippocampus'
print(roi_label[0:20])
print(roi_label[-1:3])

Solution

hippocampus
       

Sort and Sorted

roi_label_as_list = list(roi_label)

In simple terms, explain the difference between sorted(roi_label_as_list) and roi_label_as_list.sort().

Copying (or Not)

What do these two programs print? In simple terms, explain the difference between new = old and new = old[:]. For more information read about deep copy vs shallow copy

# Program A
old = list('Brain')
new = old      # simple assignment
new[0] = 'D'
print('new is', new, 'and old is', old)
# Program B
old = list('Brain')
new = old[:]   # assigning a slice
new[0] = 'D'
print('new is', new, 'and old is', old)

Key Points