Created
January 24, 2017 03:52
-
-
Save gnilchee/afe72f125c9988c3d0d21641f7267b21 to your computer and use it in GitHub Desktop.
dict and list comprehension in python
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
#!/usr/bin/env python3 | |
# my reference list | |
nums = [1,2,3,4,5,6,7,8,9,10] | |
# 'n' for each 'n' in nums list | |
my_list = [] | |
for n in nums: | |
my_list.append(n) | |
print(my_list) | |
# using list comprehension | |
my_list = [n for n in nums] | |
print(my_list) | |
# 'n'^2 for each 'n' in nums | |
my_list = [] | |
for n in nums: | |
my_list.append(n*n) | |
print(my_list) | |
# using list comprehension | |
my_list = [n*n for n in nums] | |
print(my_list) | |
# 'n' for each 'n' in nums if 'n' is even | |
my_list = [] | |
for n in nums: | |
if n%2 == 0: | |
my_list.append(n) | |
print(my_list) | |
# using list comprehension | |
my_list = [n for n in nums if n%2 == 0] | |
print(my_list) | |
# two more reference lists | |
first_name = ['Daniel', 'Greg', 'George', 'Justin'] | |
last_name = ['Brown', 'Nilchee', 'Smith', 'Bielber'] | |
# create a dict('first_name': 'last_name') based on the above lists | |
my_dict = {} | |
for first, last in zip(first_name, last_name): | |
my_dict[first] = last | |
print(my_dict) | |
# using dict comprehension | |
my_dict = {first: last for first, last in zip (first_name, last_name)} | |
print(my_dict) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment