List comprehension
Spoiler (hover to show) num_list = [1,2,3,4,5,6,7,8,9,10] new_list = [num + 1 for num in num_list] # is the same as loop_list = [] for num in num_list: added_1 = num + 1 loop_list.append(added_1) print(new_list) print(loop_list) name = "Angela" name_list = [letter for letter in name] # name_list should have each letter of the name in the list doubled_list = [num * 2 for num in range(1,5)] names = ["Alex", "Beth", "Caroline", "Dave", "Elanor", "Freddie"] short_names = [name for name in names if len(name) < 5] long_names = [name for name in names if len(name) >= 5]
Challenge
Spoiler (hover to show) #Challenge numbers = [1,1,2,3,5,8,13,21,34,55] squared_numbers = [n * n for n in numbers]
Challenge
Spoiler (hover to show) #Challenge new_numbers = [1,1,2,3,5,8,13,21,34,55] even_numbers = [n for n in new_numbers if n % 2 == 0]
Challenge
Spoiler (hover to show) #Challenge list1 = [] list2 = [] with open("file1.txt") as f1: list1 = f1.readlines() with open("file2.txt") as f2: list2 = f2.readlines() num_list1 = [int(n.strip()) for n in list1] num_list2 = [int(n.strip()) for n in list2] overlap_list = [n for n in num_list1 if n in num_list2]
Dictionary Comprehension
Spoiler (hover to show) import random names2 = ["Alex", "Beth", "Caroline", "Dave", "Elanor", "Freddie"] students_scores = {name:random.randint(1,100) for name in names2} passed_students = {student:score for (student, score) in students_scores.items() if score >= 60}
Challenge
Spoiler (hover to show) #Challenge sentence = "The wallaby is nocturnal and energetic." words = sentence.split() words_count = {word:len(word) for word in words } temp_in_c = { "Monday": 12, "Tuesday": 14, "Wednesday": 15, "Thursday": 14, "Friday": 21, "Saturday": 22, "Sunday": 24 } temp_in_f = {day:((ctemp * 9/5) * 32) for (day, ctemp) in temp_in_c.items()}
Iterate over DataFrame
Spoiler (hover to show) new_student_scores = { "students": ["Dave", "Mary", "Benny"], "scores": [34, 65, 22] } student_df = pandas.DataFrame(new_student_scores) for (index, row) in student_df.iterrows(): print(row.scores)
Project
Spoiler (hover to show) #Project nato_df = pandas.read_csv("nato_phonetic_alphabet.csv") name = "Benjamin".upper() for letter in name: for (index, row) in nato_df.iterrows(): if row.letter == letter: print(row.letter + " as in " + row.code)