Lists and Loops Slides
Lists and Loops Slides
Sarah Holderness
PLURALSIGHT AUTHOR
@dr_holderness
A List is a Container of Things
# list of lists
lists = [ ['A', 'B', 'C'], ['D', 'E', 'F'] ]
Creating a List of Internet Slang Acronyms
1st
>>> acronyms[0] 'LOL'
item
4th
>>> acronyms[3] 'TBH'
item
['LOL', 'IDK']
Now we have 2
items in the list.
Creating a List and Adding Items
We have our 2
extra items
Creating a List and Adding Items
acronyms.append('BFN')
if item in list
if 1 in [1, 2, 3, 4, 5]:
print('True')
True
Check if Exists in List
print(acronyms)
We need a loop
The Syntax of a for loop
Loop
for variable in list
expenses.py
expenses = []
With our current set
expenses.append(float(input("Enter an expense:\n")))
of tools, we would
expenses.append(float(input("Enter an expense:\n"))) type input 7 times.
expenses.append(float(input("Enter an expense:\n")))
expenses.append(float(input("Enter an expense:\n")))
Is there a way we
expenses.append(float(input("Enter an expense:\n"))) can loop 7 times
expenses.append(float(input("Enter an expense:\n"))) instead and ask for
expenses.append(float(input("Enter an expense:\n"))) input inside the
... loop?
The range() Function
0
This let’s us loop a certain
1 number of times, which is what
2 needed to enter expenses…
3
4
5
6
Adding Input to Expenses Calculator
expenses.py
total = 0
expenses = []
for i in range(7):
expenses.append(float(input("Enter an expense:")))
total = sum(expenses)
expenses.py
expenses.py
expenses.py
total = 0
expenses = []
num_expenses = int(input("Enter # of expenses:"))
Adding Input to Expenses Calculator
expenses.py