Files
jps/python/lists.py

55 lines
1.2 KiB
Python
Raw Permalink Normal View History

2020-02-17 11:57:05 -06:00
# LISTS
2020-02-17 13:05:17 -06:00
# use square brackets to get one item of a list using index.
# note that first item has index 0.
2020-02-25 08:16:53 -06:00
# to get that first item, 67, scores[0]
2020-02-17 11:57:05 -06:00
scores = [67, 32, 29]
print(scores[2])
2020-02-17 13:05:17 -06:00
print() # print blank line
2020-02-25 08:16:53 -06:00
# sum is a function built into python lists.
# if all items in the list are numeric it will add them up.
# len gives you the number of items in the list, here 3 items.
2020-02-17 11:57:05 -06:00
print(sum(scores))
print(len(scores))
2020-02-17 13:05:17 -06:00
print()
2020-02-17 11:57:05 -06:00
# USING A FOR LOOP TO ITERATE A LIST
2020-02-25 08:16:53 -06:00
# our variable for the list is scores
# we use score as a variable for list iteration.
# each time through the loop, score takes on the next value in the list
2020-02-17 11:57:05 -06:00
for score in scores:
2020-02-25 08:16:53 -06:00
if score % 2 == 0: # % is called mod, and gives you the remainder of a division
2020-02-17 11:57:05 -06:00
print(score, ' is even.')
2020-02-17 13:05:17 -06:00
print()
2020-02-17 11:57:05 -06:00
names = ["Alice", "Tina", "Berta"]
# SORTING A LIST
print(sorted(names))
# ITERATE A LIST TO FIND NAMES THAT CONTAIN C
for name in names:
if 'c' in name:
2020-02-17 13:05:17 -06:00
print(name, ' contains a c')
print()
# add an item to a list
names.append('Jenny')
print(names)
# delete Tina from the list
names.remove('Tina')
print(names)
print()
# list inside a list
scores.append([100, 103])
print(scores)
print(scores[3][0])