List Basics¶
-
Write code to create a list called
greetings
containing the string ‘hello’ and the string ‘nihao’.Use[
and]
and separate the strings with commas.
-
Write a statement to create a variable
emptyList
referring to an empty list.You can create an empty list by using[
and]
with nothing in between.
-
Write code to print the element at index 2 from a previously-defined list
groceries
.Call print(), accessing groceries inside it.
-
Write code to print the 2nd-to-last element of previously-defined list
groceries
.Use -2 to access the 2nd-to-last element.
-
Write code to create a list containing 3 elements, your name, your age, your eye color, where your name and eye color are strings, and your age is a number.Lists can contain elements of any type.
-
Write a line of code to replace the element at index 1 of a previously-defined list
groceries
with the string ‘chocolate milk’.To replace an element in a list, access that element on the left-hand-side of an assignment statement.
-
Write code that removes the first item (at index 0) from a list
groceries
and adds that item back at the end of the list.Use two lines of code. Usepop()
in the first line, andappend()
in the second.
-
Write code to remove the last item of the list
groceries
and insert it in the middle of the list. Assume the list has an odd number of elements before removing the last item (and, thus, an even number of elements after removing the last item). (Hint: use integer division//
.)Use multiple lines of code. First,pop()
the last item off and store it in a variable. Then, get the length of the list. Then insert the item back into the list in the middle.
-
Write code to swap the first and last items in the list
groceries
.Do this in 4 steps: remove the last item and store in a variable. Remove the first item and store in a variable. Then, in two lines of code, add the items back to the list, usinginsert()
andappend()
.
-
Write code to create a new list
allitems
that is the concatenation of listgroceries
and listclothes
.You can concatenate lists using+
.
-
Given a list
groceries
, print out the item from the list with the minimum value and the index of where that item is ingroceries
.Use
min(groceries)
to find the minimum item. Useindex()
to get the index of that item.The answer should be
Doritos! 3
.
-
Given a list
scores
, write code to store the average in a variable calledaverage_score
. Then, printaverage_score
.Usesum(scores)
andlen(scores)
in your computation.