lists Flashcards
how would you make a list of the heights of students in a class:
using -
Noelle is 61 inches tall
Ava is 70 inches tall
Sam is 67 inches tall
Mia is 64 inches tall
- set varible to height
- height = [61, 70, 67, 64]
What is a list in python
a list is one of the many built-in data structures that allows us to work with a collection of data in sequential order.
what does a list need to start and end with
1.A list begins and ends with square brackets ([ and ])
- Each item (i.e., 67 or 70) is separated by a comma (,)
can you combine mutiple data types in a list ?
yes
example:
mixed_list_string_number = [“Noelle”, 61]
can a list contain a string, integer, boolean, and float.
yes
example:
mixed_list_common = [“Mia”, 27, False, 0.5]
Why would we create an empty list ?
Usually, it’s because we’re planning on filling it up later based on some other input. We’ll talk about two ways of filling up a list in the next exercise.
how do you layout a list method
methods will follow the form of list_name.method(). Some methods will require an input value that will go between the parenthesis of the method ( ).
what is the function of the list method .append( )
allows us to add an element to the end of a list.
append_example = [ ‘This’, ‘is’, ‘an’, ‘example’]
append_example.append(‘list’)
print(append_example)
what method is used to add and expand to a list using the + symbol ?
items_sold_new = items_sold + [“biscuit”, “tart”]
print(items_sold_new)
Prints [‘cake’, ‘cookie’, ‘bread’, ‘biscuit’, ‘tart’]
How do you add a single element to a list
f we want to add a single element using +, we have to put it into a list with brackets ([]):
my_new_list = my_list + [4]
print(my_new_list)
# Prints [1, 2, 3, 4]
in pyhton what do we call the location of an element in a list
Index
Here are the index numbers for the list calls:
Element Index
“Juan” 0
“Zofia” 1
“Amare” 2
“Ezio” 3
“Ananya” 4
what index number does the first element =
it will always start on 0
how do you select a single element from a list ?
by using square brackets ([]) and the index of the list item. If we wanted to select the third element from the list, we’d use calls[2]:
print(calls[2])
how can you select the last element of a list?
We can use the index -1 to select the last item of a list, even when we don’t know how many elements are in a list.
Consider the following list with 6 elements:
pancake_recipe = [“eggs”, “flour”, “butter”, “milk”, “sugar”, “love”]
If we select the -1 index, we get the final element, “love”.
print(pancake_recipe[-1])
Would output:
love
how do you change a value on a list
reassign the value using the specific index.
garden[2] = “Strawberries”
print(garden)
Will output:
[“Tomatoes”, “Green Beans”, “Strawberries”, “Grapes”]