W3 Basics - Lists Flashcards
What is a namespace
Mapping from names to objects.
For instance, two modules might have an attribute/method with the same name, but they are in different namespaces
module1.example module2.example module3
I’ve created an object from a class. What can I add to the class to make the output of the below to be “Hi, my name is Jeff”
obj = Class()
print(obj)
def __str__(self):
return “Hello, my name is Jeff”
Remove whitespace at beginning and end of string
string.strip()
Replace H with J in Hello world
string.replace(‘H’, ‘J’)
Turn string into a list separating elements by a ‘,’
string.split(‘,’)
Using an f string, turn x = 55 in x = 55.00
add numbers in an fstring
print(f”{x:.2f} {22 + 50}”)
Give a word double quotes with an escape character
“We are "vikings" today”
Using an if statement see if ‘apple’ is in a list
if ‘apple’ in list:
if ‘apple’ not in list:
Change second list item
If list has 6 elements, change the 2nd and 3rd item to ‘watermelon’ and ‘grape’
list[1] = ‘blue’
list[1:3] = [ ‘watermelon’, ‘grape’ ]
If you insert more elements then your replace, what is the output:
thislist = [“apple”, “banana”, “cherry”]
thislist[1:2] = [“blackcurrant”, “watermelon”]
[‘apple’, ‘blackcurrant’, ‘watermelon’, ‘cherry’]
Add list item ‘watermelon’ to a list with three entries. It should go in the second spot and erase the third entry
add ‘watermelon’ to the third spot using a method
list[1:3] = [‘watermelon’]
list.insert(2, ‘watermelon’)
Append items in ‘tropical’ to ‘thislist’
thislist.extend(tropical)
If you append tuples or sets they’ll still come out as list items.
There are four ways to delete lists
via string
2 via index
deleting the list itself
deleting all the list’s contents
Perform all of these steps
list.remove(‘’)
list.pop(2)
list.pop() removes last item
del list[2]
del list
list.clear()
Using some python skills, create a loop that iterates through all list indices. Remember, you want to do this via INDICES
list = [‘this’, ‘that’, ‘other’]
for i in range(len(list)):
print(list[])
OR
i = 0
while i < len(list):
print(list[i]
i += 1
Loop through a list using list comprehension
[print(x) for x in list]