Skip to content

Instantly share code, notes, and snippets.

@guestPK1986
Created August 30, 2020 20:32
Show Gist options
  • Save guestPK1986/421eb62ae245793e07a3245fd5e7916f to your computer and use it in GitHub Desktop.
Save guestPK1986/421eb62ae245793e07a3245fd5e7916f to your computer and use it in GitHub Desktop.
list, set, dictionary comprehension exercises
#create a LIST of characters in string 'hello'
my_list = [i for i in 'hello']
print("my_list "+ str(my_list))
#create a LIST of numbers in tuple (1,2,3,4)
new_tuple = [i for i in (1,2,3,4)]
print("new_tuple " + str(new_tuple))
#create a SET of unique items from string
a_set = {i for i in 'hello'}
print("a_set " + str(a_set))
#create a LIST of characters in string 'hello'
string = []
for i in 'hello':
string.append(i)
print(string)
#create a LIST of numbers in range(0,100)
my_list2 = [num for num in range(0,100)]
print("my_list2 " + str(my_list2))
#create a LIST of numbers**2 in range(0,100)
my_list3 = [num**2 for num in range(0,100)]
print("my_list3 " + str(my_list3))
#create a LIST of even numbers**2 in range(0,100)
my_list4 = [num**2 for num in range(0,100) if num%2 ==0]
print("my_list4 " + str(my_list4))
#create a SET of numbers in range(0,100)
my_list5 = {num for num in range(0,100)}
print("my_list5 " + str(my_list5))
#using a sample_dict create a new dictionary where each value will be squared
simple_dict = {
'a':1,
'b':2,
'c':3
}
my_dict = {key:value**2 for key, value in simple_dict.items() }
print("my_dict " + str(my_dict))
#using a sample_dict create a new dictionary where each value will be squared, return only even numbers
your_dict = {k:v**2 for k, v in simple_dict.items()if v%2 ==0 }
print("your_dict " + str(your_dict))
#create a SET of numbers from list [1,2,3] where each item will be multiplied by 2
my_dictr = {i:i*2 for i in [1,2,3]}
print("my_dictr " + str(my_dictr))
#create a new LIST of duplicates from some_list
some_list = ['a', 'b', 'c', 'd', 'e', 'f','a', 'b', 'c','a', 'b', 'c' ]
dupl=[]
new = [dupl.append(i) for i in some_list if some_list.count(i)>1 if i not in dupl]
print(dupl)
#OR
new = list(set([i for i in some_list if some_list.count(i)>1]))
print(dupl)
#create a new SET of duplicates from some_list
duplicates = set([i for i in some_list if some_list.count(i)>1])
print(duplicates)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment