Write a list comprehension (one line of Python code) to create the following lis
ID: 671536 • Letter: W
Question
Write a list comprehension (one line of Python code) to create the following lists:
a) List of even numbers from 1-100.
b) A list of the cubed values of all odd numbers from 1-25.
Given list1 = ["apple", "pear", "lemon", "blueberry"] and list2 = ["orange", "pineapple", "avocado", banana"]
c) Write the list comprehension to gather all words with two of the same consonants in a row.
d) Write the list comprehension to gather all words starting with either m, o, or p.
e) Write the list comprehension to print the pairs of fruits (one from list1 and one from list2) if the fruits do not start with the same letter (should create a list of [('apple', 'orange'), ('lemon', 'avocado')].
Explanation / Answer
list1 = ["apple", "pear", "lemon", "blueberry"];
list2 = ["orange", "pineapple", "avocado", "banana"];
#part c
M = []
for i in range(len(list1)):
word_1 = list1[i]
for j in range(len(list2)):
word_2 = list2[j]
count = 0
for ch_1 in word_1:
if (ch_1 not in ('a', 'e', 'i', 'o', 'u')):
for ch_2 in word_2:
if (ch_2 == ch_1):
count += 1;
break;
if (count == 2):
M.append(word_1)
M.append(word_2)
print list(set(M))
print
print
# part d
M = [x for x in list1 if (x[0] == 'm' or x[0] == 'o' or x[0] == 'p')]
N = [x for x in list2 if (x[0] == 'm' or x[0] == 'o' or x[0] == 'p')]
print M+N
print
print
# part e
M = [(x,y) for x in list1 for y in list2 if (x[0] != y[0])]
print M
print
print
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.