Sequence Types
Sequence Types
6.0001 LECTURE 3
2
STRINGS
6.0001 LECTURE 3
3
s = "abc"
len(s) → evaluates to 3
In addition to accessing list elements one at a time, concise syntax to access sublists; this is known as slicing
6.0001 LECTURE 3
Slicing
20
Slicing Example
6.0001 LECTURE 3
s = "abcdefgh"
5
s[3:6]
→ evaluates to "def", same as
s[3:6:1]
s[3:6:2] → evaluates to "df"
s[::]
s[::-1]
→ evaluates to "abcdefgh", same as s[0:len(s):1]
→ evaluates to "hgfedbca", same as s[-1:-(len(s)+1):-1]
s[4:1:-2] → evaluates to "ec"
STRINGS
6.0001 LECTURE 3
6
to get the value at a certain index/position
s = "abc"
s[0] | → | evaluates to "a" |
s[1] | → | evaluates to "b" |
s[2] | → | evaluates to "c" |
s[3] | → | trying to index out of bounds, error |
s[-1] | → | evaluates to "c" |
s[-2] s[-3] | → → | evaluates to "b" evaluates to "a" |
index: index:
0 1 2 → indexing always starts at 0
-3 -2 -1 → last element always at index -1
Slicing and Combining Strings
6.0001 LECTURE 3
7
Given: A string s of length at most 200 letters and four integers a, b, c and d.
Return: The slice of this string from indices a through b and c through d
(with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.
Sample Dataset
HumptyDumptysatonawallHumptyDumptyhadagreatfallAlltheKingshorsesandalltheKingsmenCouldntputHumptyDumptyinhisplaceagain. 22 27 97 102
Sample Output
Humpty Dumpty
EXERCISE: Reversing a sequence
6.0001 LECTURE 3
8
Write a program that starts with a word, reverse it.
Pictorial Presentation:
word = “something”�rword = “”��… do stuff��print(“reversed word: “, rword)��
nums = list(range(5)) # range is a built-in function
# that creates a list of integers
print(nums) # Prints "[0, 1, 2, 3, 4]"
print(nums[2:4]) # Get a slice from index 2 to 4
# (exclusive); prints "[2, 3]"
print(nums[2:]) # Get a slice from index 2 to the
# end; prints "[2, 3, 4]"
print(nums[:2]) # Get a slice from the start to
# index 2 (exclusive); prints "[0, 1]"
print(nums[:]) # Get a slice of the whole list;
# prints "[0, 1, 2, 3, 4]"
print(nums[:-1]) # Slice indices can be negative; prints
# "[0, 1, 2, 3]"
nums[2:4] = [8, 9] # Assign a new sublist to a slice
print(nums) # Prints "[0, 1, 8, 9, 4]"
SLICING
Strings vs Lists
6.0001 LECTURE 3
s = "hello"
s[0] = 'y'
s = 'y'+s[1:len(s)]
→ gives an error
→ is allowed
s
"hello"
"yello"
10
for LOOPS
6.0001 LECTURE 3
11
for var in range(4):
<expressions>
→ var iterates over values 0,1,2,3
→ expressions inside loop executed with each value for var
for var in range(4,6): → var iterates over values 4,5
<expressions>
STRINGS AND LOOPS
6.0001 LECTURE 3
12
s = "abcdefgh"
for index in range(len(s)):
if s[index] == 'i' or s[index] == 'u': print("There is an i or u")
for | char in s: | |
| if char == 'i' or char print("There is an | == 'u': i or u") |
CODE EXAMPLE:
an_letters = "aefhilmnorsxAEFHILMNORSX"
word = ”w!o%r?d”
i = 0
while i < len(word): char = word[i]
if char in an_letters:
print(char + “is a letter")
else:
print(char + “is not a letter”)
i += 1
for char in word:
EXERCISE: printing the common letters in a string
6.0001 LECTURE 3
14
s1 = "this is a string"
s2 = "xyz are letters"
for char1 in s1:
for char2 in s2:
if char1 == char2:
print("common letter: “ + char1)
else:
print(uncommon letters: “ char1 + char2)
animals = ['cat', 'dog', 'monkey’]
for animal in animals:
print(animal)
# Prints "cat", "dog", "monkey", each on its own line.
LOOPS
EXERCISE
Take two lists, say for example these two:
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
Make sure your program works on two lists of different sizes.
TUPLES
6.0001 LECTURE 5
te = ()
t = (2,"foo",3) t[0]
(2,"foo",3) + (5,6)
evaluates to 2
evaluates to (2,"foo",3,5,6)
→ slice tuple, evaluates to ("foo",)
t[1:2]
t[1:3]
len(t)
→ slice tuple, evaluates to ("foo",3)
→ evaluates to 3
t[1] = 4 → gives error, can’t modify object
17
MANIPULATING TUPLES
6.0001 LECTURE 5
aTuple:(( ),( ),( ))
nums = ()
words = ()
for t in aTuple: nums = nums +
(t[0],)
if t[1] not in words:
words = words + (t[1],)
min_n = min(nums) max_n = max(nums)
unique_words = len(words)
newTuple = (min_n, max_n, unique_words)
nums( )
words(
if not already in words
i.e. unique strings from aTuple
18
? ?
? )
LISTS
6.0001 LECTURE 5
19
INDICES AND ORDERING
6.0001 LECTURE 5
a_list = []
L = [2, 'a', 4, [1,2]]
→ evaluates to 4
→ evaluates to 2
→ evaluates to 5
→ evaluates to [1,2], another list!
→ gives an error
len(L)
L[0]
L[2]+1
L[3]
L[4]
i = 2 L[i-1]
→ evaluates to ‘a’ since L[1]='a' above
20
CHANGING ELEMENTS
6.0001 LECTURE 5
L = [2, 1, 3]
L[1] = 5
21
ITERATING OVER A LIST
6.0001 LECTURE 5
to len(L)-1
to n-1
total = 0
for i in range(len(L)): total += L[i]
print total
total = 0
for i in L:
total += i print total
10
OPERATIONS ON LISTS - ADD
6.0001 LECTURE 5
23
L = [2,1,3]
L.append(5)
→ L is now [2,1,3,5]
OPERATIONS ON LISTS - ADD
6.0001 LECTURE 5
24
L1 | = | [2,1,3] | | |
L2 | = | [4,5,6] | | |
L3 | = | L1 + L2 | → | L3 is [2,1,3,4,5,6] L1, L2 unchanged |
L1.extend([0,6])
→ mutated L1 to [2,1,3,0,6]
OPERATIONS ON LISTS -
REMOVE
6.0001 LECTURE 5
25
L = [2,1,3,6,3,7,0] # do below in order L.remove(2) → mutates L = [1,3,6,3,7,0] L.remove(3) → mutates L = [1,6,3,7,0]
del(L[1])
L.pop()
→ mutates L = [1,3,7,0]
→ returns 0 and mutates L = [1,3,7]
CONVERT LISTS TO STRINGS
AND BACK
6.0001 LECTURE 5
26
character from s an element in L
s = "I<3 cs" list(s) s.split('<')
L = ['a','b','c']
''.join(L)
'_'.join(L)
→ s is a string
→ returns ['I','<','3',' ','c','s']
→ returns ['I', '3 cs']
→ L is a list
→ returns "abc"
→ returns "a_b_c"
OTHER LIST OPERATIONS
6.0001 LECTURE 5
27
L=[9,6,0,3]
L.sort() L.reverse()
→ mutates L=[0,3,6,9]
→ mutates L=[9,6,3,0]
LISTS IN MEMORY
6.0001 LECTURE 5
28
side effects
ALIASES
6.0001 LECTURE 5
29
CLONING A LIST
6.0001 LECTURE 5
chill = cool[:]
20
SORTING LISTS
6.0001 LECTURE 5
31
mutates the list, returns nothing
LISTS OF LISTS OF LISTS….
6.0001 LECTURE 5
32
MUTATION AND ITERATION
6.0001 LECTURE 5
33
for e in L1:
if e in L2:
L1.remove(e)
L1 = [1, 2, 3, 4]
L2 = [1, 2, 5, 6]
remove_dups(L1, L2)
Why?
L1_copy = L1[:]
for e in L1_copy: if e in L2:
L1.remove(e)
EXERCISE
Write a program that takes a list, and returns two new lists with the input list values in sorted and reverse sorted order.
Module Questionnaire
Funding Sources: NIH U24 EB028887, NSF 2120200, 2000281, 1720625
Previous Funding : NIH R01 GM122424
Please take a minute or two to let us know about your experience with this module by filling out the brief zoom survey
Feel free to provide additional comments and suggestions in the slack or by email to us as well (hfennel@iu.edu)