Last active
August 22, 2020 09:54
-
-
Save rogfrich/f9a18abcf36ccb65c1713dd8e9130847 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
A series of examples of list operations for Dad! | |
EXAMPLE 1 | |
Start with a list of three lists: [[1,2,3], [4,5,6], [7,8,9]] | |
End with new lists for each position in the old list. | |
""" | |
# a list of lists, each three items long. | |
old_list = [ | |
[1, 2, 3], | |
[4, 5, 6], | |
[7, 8, 9], | |
] | |
# list comprehensions to selectively add items from old_list | |
first_items = [x[0] for x in old_list] | |
second_items = [x[1] for x in old_list] | |
third_items = [x[2] for x in old_list] | |
# check it works... | |
print( | |
first_items, | |
second_items, | |
third_items, | |
) | |
# you can filter the comprehension using a conditional statement | |
some_first_items = [x[0] for x in old_list if x[0] > 1] | |
# check it works... should be [4, 7] | |
print(some_first_items) | |
""" | |
EXAMPLE 2 | |
Start with three lists: [x,x,x], [y,y,y], [z,z,z]. | |
End with [x,y,z], [x,y,z], [x,y,z] | |
""" | |
list1 = [1, 1, 1] | |
list2 = [2, 2, 2] | |
list3 = [3, 3, 3] | |
# use zip() to create a zip iterable that we can iterate over: each iteration will be a tuple of the next values in each of the source lists | |
zip_object = zip(list1, list2, list3) | |
for i in zip_object: | |
print(i) # or do something more useful... | |
# you can shorten the above to: | |
for i in zip(list1, list2, list3): | |
print(i) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment