π Week 2 - Lab Intro#
In this lab introduction we will briefly revisit some of the key topics from lecture and discuss the map function, which is used in the lab assignment.
Strings#
The string data type stores a string of characters. Create a string by enclosing text in single or double quotes.
s1 = "This is an example string"
s2 = 'So is this'
Find the string length with len()
.
alphabet = "abcdefghijklmnopqrstuvwxyz"
print(len(alphabet))
The position of each letter in a string is called its index and starts at 0
You can also use negative indices. A negative index counts from the end.
# Get the 1st letter of the alphabet
print(alphabet[0])
# Get the 4th letter of the alphabet
print(alphabet[3])
# Get the 26th letter of the alphabet
print(alphabet[25])
# Get the 26th letter of the alphabet
print(alphabet[len(alphabet)-1])
# Get the 26th letter of the alphabet
print(alphabet[-1])
# Get the 25th letter of the alphabet
print(alphabet[-2])
# Get the 1st letter of the alphabet
print(alphabet[-len(alphabet)])
You can slice strings by supplying indices in square brackets.
To slice a list L
from a start index start
up to (but not including) index stop
with a step size of step
, do the following:
L[start:stop:step]
# Slice from index 0 up to (not including 5)
print(alphabet[:5])
# You can also write this as:
print(alphabet[0:5])
# Slice from index 5 to the end
print(alphabet[5:])
# You can also write this as:
print(alphabet[5:len(alphabet)])
# Slice from index 0 to the end, stepping by 2
print(alphabet[::2])
# You could also write this as:
print(alphabet[0:len(alphabet):2])
# Reverse a string
print(alphabet[::-1])
You can use f-string formatting to easily include variable values in a string
year = 2024
year_message = f"The current year is {year}."
print(year_message)
Lists and dictionaries#
Lists are ordered collections of data. Dictionaries are a data structure that have (key, value) pairs.
# this is a list
L = ["abc", 42, True]
# this is a dictionary
D = {
"color": "green",
"number": 12,
"result": True
}
Square brackets are used to access values in a list or dictionary.
# get the list item at index 1
print(L[1])
# get the dictionary item at key "color"
print(D["color"])
Map function#
We can use the map function to apply the same function to all elements of a list.
Example: squaring a list of numbers#
# a simple fucntion that squares a number
def square(x):
return x**2
L = [0,1,2,3,4,5,6,7,8,9,10]
print(map(square, L))
The map function returns a map object that can be converted to a list as follows:
squared_L = list(map(square, L))
print(squared_L)