CS 3 Ans - Python List
CS 3 Ans - Python List
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers
print(sum_list([1,2,-8]))
def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot
print(multiply_list([1,2,-8]))
5. Write a Python program to count the number of strings where the string
length is 2 or more and the first and last character are same from a
given list of strings.
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2
def match_words(words):
ctr = 0
# Dictionary
x = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6}
print (sorted(x))
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print (sorted(x))
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print (sorted(x))
def func(x):
return x % 7
L = [15, 3, 11, 7]
Answer
def last(n): return n[-1]
def sort_list_last(tuples):
return sorted(tuples, key=last)
print(sort_list_last([(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]))
a = [10,20,30,20,10,50,60,40,80,50,40]
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Alternate Answer
original_list = [10, 22, 44, 23, 4]
new_list = original_list.copy()
print(original_list)
print(new_list)
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.
def common_data(list1, list2):
result = False
for x in list1:
for y in list2:
if x == y:
result = True
return result
print(common_data([1,2,3,4,5], [5,6,7,8,9]))
print(common_data([1,2,3,4,5], [6,7,8,9]))
12. Write a Python program to print a specified list after removing the
0th, 4th and 5th elements.
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
# enumerate Example
l1 = ["eat","sleep","repeat"]
s1 = "geek"
print (list(enumerate(l1)))
print (list(enumerate(s1)))