ITEC-425 / SENG-425: Python Programming Lab Lab 8: Lists and Dictionaries Task 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

ITEC-425 / SENG-425: Python Programming Lab

Lab 8: Lists and Dictionaries


Task 1
Write Python code to print the numbers in the list given below after removing even
numbers from it.

num_list = [3, 1, 18, 4, 11, 10, 6, 20]

In [1]:
# method 1 using for loop

num_list = [3, 1, 18, 4, 11, 10, 6, 20]


out_list = []

for num in num_list:


if num % 2 != 0:
out_list.append(num)

print('num_list = ', num_list)


print('out_list = ', out_list)

num_list = [3, 1, 18, 4, 11, 10, 6, 20]


out_list = [3, 1, 11]

Task 2
Rewrite the above Python code, using list comprehension method, to print the numbers in
the list given below after removing even numbers from it.

num_list = [3, 1, 18, 4, 11, 10, 6, 20]

In [2]:
# method 2 - using list comprehension

num_list = [3, 1, 18, 4, 11, 10, 6, 20]


out_list = [i for i in num_list if i%2 != 0]

print('num_list = ', num_list)


print('out_list = ', out_list)

num_list = [3, 1, 18, 4, 11, 10, 6, 20]


out_list = [3, 1, 11]

Task 3
Write Python code that takes a list of nums and displays the product of all numbers in the
lsit.

In [3]:
num_list = [3, 1, 18, 4, 11, 10, 6, 20]

prod = 1
for num in num_list:
prod = prod * num

print('num_list=', num_list)
print('product of numbers:', prod)

num_list= [3, 1, 18, 4, 11, 10, 6, 20]


product of numbers: 2851200

Task 4
Write python code to do the following, using the list given below:

get the smallest number


get the largest number
get the size or length of the list
get the sum of all numbers in the list

num_list = [3, 1, 18, 4, 11, 10, 6, 20]

In [4]:
# write your code here

Task 5
Write Python code to take a list of characters and convert it into a string.

char_list = ['y', 'e', 'l', 'l', 'o', 'w']

In [5]:
# write your code here

Task 6
Write Python code that takes the two list given below, and joins them to create a new list,
sort the new list and display it.

list1 = [3, 1, 18, 4]


list2 = [11, 10, 6, 20]

Expected output:

list1 = [3, 1, 18, 4]


list2 = [11, 10, 6, 20]
new_list = [1, 3, 4, 6, 10, 11, 18, 20]

In [7]:
# write your code here

Task 7
Write Python code that asks the user to input a string message, and uses a dictionary to
create a word frequency map.
In [8]:
msg = input("Enter your message:")

words = msg.split()

wd_counts = dict()

for w in words:
wd_counts[w] = wd_counts.get(w, 0) + 1

print("Word frequency map for your message is: \n")


print(wd_counts)

Enter your message:to be or not to be


Word frequency map for your message is:

{'to': 2, 'be': 2, 'or': 1, 'not': 1}

Task 7
Write Python to that uses the given dictionary and does the following:

d = {'apples': 4, 'organges': 10, 'bananas': 5, 'pears': 7}

print a list of all keys


print a list of all values

In [9]:
# write your code here

You might also like