Lecture 9 : Lists
len(alist) = gives you the length of a list
To iterate a whole list:
For i in range(len(alist)):
print(alist[i])
Or
For i in alist:
print(i)
To add two lists together → [1, 2] + [3, 54. 43. 9] = [1, 2, 3, 54, 43, 9]
Example:
List1 = [1, 2]
List2 = [3, 5, 43, 9]
List3 = List1 + List 2 → print(List3) = [1, 2, 3, 54. 43. 9]
To multiply values in a list (repeats it x amount of times doesn’t multiply values)
List3 = List1 * 4 → print(List3) = [1, 2, 1, 2, 1, 2, 1, 2]
List3 = (List1 * 4) + List2 → print(List3) = [1, 2, 1, 2, 1, 2, 1, 2, 3, 54, 43, 9]
➢ list.append(x) Add item x to the end of the list
➢ list.insert(i,x) Insert item x at position i in list
➢ list.remove(x) Remove first item with value of x
➢ list.pop(i) Remove item at i and return it
➢ list.pop() Remove last item and return it
➢ list.clear() Remove all items from the list
➢ list.sort() Sorts the elements of a list
➢ sorted(list) Returns sorted list without changing the original version
Only pop() and pop(i) return values without needing to use the print function.
‘In’ operator:
mylist = [ “alice”, 2, True, [17, 19] ]
2 in mylist → True
16 in mylist → False
True in mylist → True
[17, 19] in mylist → True
[19] in mylist → False
Can be useful in a while or for loop
Slicing [start:end] like range, starts at “start” ends right before “end”
List[:] (no end value, keeps going for the entire length) → print(List) = [5, 3, 4, 5, 5, 1, 2, 7, 10]
List[2 : 5] → print(List) = [4, 5, 5]
Lecture 10 String operations
• "12".isdigit() returns True (since 12 is a non-negative integer)
• "mY StriNg".lower() returns "my string"
• "mY StriNg".upper() returns "MY STRING"
• "abc".isalpha() returns True (since all characters are letters)
• "my string".isalpha() returns False (since " " space is not a letter)
Removing elements in a string
str.strip(“ ”) Removes the imputed characters in the string
String1 = “hi how are you?”
String1.strip(“hoe”) → ‘i w ar yu’
Replacing elements in a string
str.replace(old, new) all occurrences of substring old replaced by substring new
Finding elements in a string
str1.startswith( ) returns True if the string does start with a specific character
str1.endswith( ) returns True if the string does end with a specific character
Can also add str1.starts/endswith(anotherstring) to see if the characters match
Two ways to find out how many times a string appears:
str1.find(string) Returns how many times a string is found, if it doesn’t exist, returns -1
str1.count(string) Returns the # of times the value is found
Separating a string into a list,
str1.split(str2 = “ ”) breaks str1 where str2 is found and returns a list
Putting that separated list back into a string
str1.join() function takes a list of strings and combines them together with a joiner string (str1) inbetween
EXTRA:
If you forget any, type help(str) to list all the methods available
Lecture 11 main() and modules
Add all your built-in functions into main( ), In the proper order;
Def main( ):
instructions( )
Startgame ( )
Playagain ( )
then end the program with to make sure code runs smoothly
If__name__ == “__main__”:
main( )
If you want python to input all the aspects of a module add a “ * “ (sometimes its redundant and doesn’t work
properly don't always add it)
Renaming a module when importing
Import turtle as T → now you can refer to turtle as T when writing the rest of your code
Lecture 14 File I/O
This only works if the file being modified is in the same folder as the current file!
I, input: user input with input( ) → O, output: user output with output( )
Two types of encoding:
1. Text (ASCII)
→ structured (easily read with an algorithm; “Book. 11.99”),
2. Binary (pdf, image files, audio files, etc)
→ unstructured (natural text can't be read easily; “The book was 11.99”)
Open/Close a file in python
f = open(filename, mode) ⟶ f.close( )
State this, to “prep” the file THEN add the modes below
OR To close the file automatically when we’re done modifying just add “with” before it! As a function
↳ with open(filename, mode) as file:
then add code below this as normal the same way you would a built in function
Can also do this to open multiple files at a time and using different modes
with open(f.txt, ‘r’) as f, open(h.txt, ‘w’) as h:
Info = f.readlines( )
for line in Info:
h.write( line.strip.lower() + ‘\n’ )
#this reads file f.txt and writes in the same data into file h.txt then automatically closes both programs when done
#h.write( line.strip.lower() + ‘\n’ )
Different types of modes:
- Reading: ‘r’ as mode, reads the file in the parameter starting from the top down
Different types of reading modes
1. f.read( ), reads and returns the entire file data
2. f.readlines( ), reads and returns the entire file data as a list however includes “\n”,
will have to list.pop( ) test this
3. f.readline( ), reads and returns only the following line with “\n”
WILL print an empty string if the next line is the end of the file (therefore there’s no data)
To avoid this add:
line = file.readline( )
While line != “ “
print(line)
line = file.readline( )
file.close( ) ⟶ closes the file and ends session once read mode reaches the end of the file
Read the entire file (not line by line) with a for loop:
for line in file:
print(line)
file.close( )
- Writing: ‘w’ as mode, creates a new file for writing, if file in input already exists it deletes it and restarts
use f.write( ) , if you want it to write on a new line add \n
f.write(“Hi how are you\n”)
- Appending: ‘a’ as mode, creates a new file for writing, if file in input already exists it adds data at the
bottom
Example with write mode:
f = open(“myfirstcode.py”, “w”)
f.write(“Great job!”)
if you want it to be on another line
f.write(“Great job!\n”)
If you want it to skip a line then write
f.write( )
f.write(“Great job!”)
Or write THEN skip a line
f.write(“Great job!”)
f.write( )