List Exercise PYTHON
List Exercise PYTHON
List Exercise PYTHON
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]
10. Write a Python program to find the list of words that are longer
than n from a given list of words.
11. Write a Python function that takes two lists and returns True if
they have at least one common member.
12. Write a Python program to print a specified list after removing the
0th, 2nd, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
16. Write a Python program to generate and print a list of first and last
5 elements where the values are square of numbers between 1 and 30
(both included).
17. Write a Python program to generate and print a list except the first
5 elements, where the values are square of numbers between 1 and 30
(both included).
18. Write a Python program to get the difference between the two
lists.
Answers
Prog 1:
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
Prog 2:
def multiply_list(items):
tot = items[0]
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
Prog 3:
Prog 4:
1. def smallest_num_in_list( list ):
2. min = list[ 0 ]
3. for a in list:
4. if a < min:
5. min = a
6. return min
7. print(smallest_num_in_list([1, 2, -8, 0]))
Prog 5:
def match_words(words):
ctr = 0
for word in words:
if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr
Prog 6:
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
Prog 7:
1. a = [10,20,30,20,10,50,60,40,80,50,40]
2.
3. dup_items = set()
4. uniq_items = []
5. for x in a:
6. if x not in dup_items:
7. uniq_items.append(x)
8. dup_items.add(x)
9.
10. print(dup_items)
Prog 8:
l = []
if not l:
print("List is empty")
Prog 9:
Prog 10:
print(long_words(3, "The quick brown fox jumps over the lazy dog"))
Prog 11:
print(common_data([1,2,3,4,5], [6,7,8,9]))
Prog 12:
1. color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
2. color = [x for (i,x) in enumerate(color) if i not in (0,4,5)]
3. print(color)
Prog 13:
array = [[ ['*' for col in range(6)] for col in range(4)] for row in range(
3)]
print(array)
Prog 14:
1. num = [7,8, 120, 25, 44, 20, 27]
2. num = [x for x in num if x%2!=0]
3. print(num)
Prog 15:
print(color)
Prog 16:
def printValues():
l = list()
for i in range(1,21):
l.append(i**2)
print(l[:5])
print(l[-5:])
printValues()
Prog 17:
1. def printValues():
2. l = list()
3. for i in range(1,21):
4. l.append(i**2)
5. print(l[5:])
6.
7. printValues()
Prog 18:
list1 = [1, 2, 3, 4]
list2 = [1, 2]
print(list(set(list1) - set(list2)))
Prog 19:
Prog 20:
Prog 21:
Prog 22:
list1 = [1, 2, 3, 0]
list2 = ['Red', 'Green', 'Black']
final_list = list1 + list2
print(final_list)
Prog 23:
import random
color_list = ['Red', 'Blue', 'Green', 'White', 'Black']
print(random.choice(color_list))