Docsity

Lecture Notes for CPSC 121 Fall 2012: Exam 2 Overview and List Slices, Study notes of Computer Science

Partial preview of the text

Download Lecture Notes for CPSC 121 Fall 2012: Exam 2 Overview and List Slices and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • Exam 2 overview
  • Slices

Reminder

  • Exam 2 (wed.)

Exam 2 Overview

Basics

  • 10% of final grade
  • ≈ 6 questions
  • closed book & notes

Topics

  • fruitful functions (return statement)
  • input function
  • type conversion functions (int, float, etc.)
  • lists
  • string and list operations (+, *, [], etc.)
  • for loops
  • range function
  • slices (today)

List slices

A slice is a sublist (or substring)

The slice operator [i:j] returns subsequences

  • The subsequence starts at index i and ends at j-1 (or len-1)
  • Omitting the first index starts the slice at index 0
  • Omitting the last index makes the slice go to (and include) the last value

a_list = [10, 20, 30, 40, 50]

a_list[0:5] [10, 20, 30, 40, 50]

a_list[1:4] [20, 30, 40]

a_list[2:3] [30]

a_list[2:2] []

a_list[:4] [10, 20, 30, 40]

a_list[2:] [30, 40, 50]

a_list[0:-1] [10, 20, 30, 40, 50]

a_list[0:200] [10, 20, 30, 40, 50]

a_list[-1:10]

a_list[:] [10, 20, 30, 40, 50]

a list[:] does a “shallow” copy of the list

  • What do you think this means?

An example:

list1 = [’python’, ’is’, [’fun’, ’easy’]]

list2 = list1[:]

list [’python’, ’is’, [’fun’, ’easy’]]

list [’python’, ’is’, [’fun’, ’easy’]]

list2[2][1] = ’hard’

list [’python’, ’is’, [’fun’, ’hard’]]

list [’python’, ’is’, [’fun’, ’hard’]]