0% found this document useful (0 votes)
46 views

CS 3 Ans - Python List

The document provides 12 examples of Python programs that perform various list operations and functions. These include summing and multiplying list items, finding the largest/smallest item, counting strings by length/character, sorting lists by tuple elements, removing duplicates, checking for empty lists, cloning lists, filtering by length, checking for common items, and removing specific indices. Various list methods like for loops, if statements, list comprehensions, and enumerate are demonstrated.

Uploaded by

asha.py81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
46 views

CS 3 Ans - Python List

The document provides 12 examples of Python programs that perform various list operations and functions. These include summing and multiplying list items, finding the largest/smallest item, counting strings by length/character, sorting lists by tuple elements, removing duplicates, checking for empty lists, cloning lists, filtering by length, checking for common items, and removing specific indices. Various list methods like for loops, if statements, list comprehensions, and enumerate are demonstrated.

Uploaded by

asha.py81
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

1. Write a Python program to sum all the items in a list.

def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_numbers

print(sum_list([1,2,-8]))

2. Write a Python program to multiplies all the items in a list

def multiply_list(items):
tot = 1
for x in items:
tot *= x
return tot

print(multiply_list([1,2,-8]))

3. Write a Python program to get the largest number from a list.


def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max

print(max_num_in_list([1, 2, -8, 0]))

4. Write a Python program to get the smallest number from a list.


def smallest_num_in_list( list ):
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
print(smallest_num_in_list([1, 2, -8, 0]))

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

for word in words:


if len(word) > 1 and word[0] == word[-1]:
ctr += 1
return ctr

print(match_words(['abc', 'xyz', 'aba', '1221']))

6. Write a Python program to get a list, sorted in increasing order by the


last element in each tuple from a given list of non-empty tuples.
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]
Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

Parameters for the sorted() function


sorted() can take a maximum of three parameters:
● iterable - A sequence (string, tuple, list) or collection
(set, dictionary, frozen set) or any other iterator.
● reverse (Optional) - If True, the sorted list is reversed (or sorted in
descending order). Defaults to False if not provided.
● key (Optional) - A function that serves as a key for the sort comparison.
Defaults to None.
Examples -1
x = [2, 8, 1, 4, 6, 3, 7]

print ("Sorted List returned :"),


print (sorted(x))

print ("\nReverse sort :"),


print (sorted(x, reverse = True))

# 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))

Examples -2 – sort based on length of string

L = ["cccc", "b", "dd", "aaa"]

print ("Normal sort :", sorted(L))

print ("Sort with len :", sorted(L, key = len))

Examples -3 – sort based on user defined function

def func(x):
return x % 7

L = [15, 3, 11, 7]

print ("Normal sort:", sorted(L))


print ("Sorted with key:", sorted (L, key = func))

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)]))

7. Write a Python program to remove duplicates from a list.

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)

8. Write a Python program to check a list is empty or not.


l = []
if not l:
print("List is empty")

9. Write a Python program to clone or copy a list.

original_list = [10, 22, 44, 23, 4]


new_list = list(original_list)
print(original_list)
print(new_list)

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.

def long_words(n, str):


word_len = []
txt = str.split(" ")
for x in txt:
if len(x) > n:
word_len.append(x)
return word_len

print(long_words(3, "The quick brown fox jumps over the lazy


dog"))

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']

List comprehensions are a concise way to create lists. They are


used to create a new list by iterating over another list.
Enumerate() method adds a counter to an iterable and returns it in a
form of enumerate object. This enumerate object can then be used
directly in for loops or be converted into a list of tuples using list()
method.

color = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']


color = [x for (i,x) in enumerate(color) if i not in (0,4,5)]
print(color)

# enumerate Example

l1 = ["eat","sleep","repeat"]
s1 = "geek"

# creating enumerate objects


obj1 = enumerate(l1)
obj2 = enumerate(s1)
print (obj1)
print (obj2)

print (list(enumerate(l1)))

print (list(enumerate(s1)))

# changing start index to 2 from 0


print (list(enumerate(s1,2)))

You might also like