Provide your own examples of the following using Python lists. Create your own examples.
Provide the Python code and output for your program and all your examples.
# test string
test_string = "Hello this is a test string to convert to list"
print(test_string)
# convert to list using 'split'
print("\n converting string to list")
word_list = test_string.split(" ")
print(word_list)
print("\nremoving items 4 different ways")
# remove item using 'remove'
word_list.remove("this")
print(word_list)
# remove item using 'pop'
word_list.pop(3)
print(word_list)
# remove item using 'del'
del word_list[2]
print(word_list)
# remove item using 'filter'
word_list = list(filter(lambda x: x != "convert", word_list))
print(word_list)
# sort values
print("\n sorting")
word_list.sort()
print(word_list)
print("\n adding items 4 different ways")
# add item using 'append'
word_list.append('one')
print(word_list)
# add item using '+'
word_list = word_list + ["two"]
print(word_list)
# add item using 'insert'
word_list.insert(1, "three")
print(word_list)
# add item using 'extend'
word_list.extend(["four"])
print(word_list)
# list to string
print("\nconvert list to string")
updated_string = " ".join(word_list)
print(updated_string)
# nested lists: matrix addition
print("\nnested lists: matrix multiplication")
def print_matrix(matrix):
for idx1 in range(len(matrix)):
for idx2 in range(len(matrix[idx1])):
print(str(matrix[idx1][idx2]), end=' ')
print("")
matrix4x3_1 = [
[4, 8, 6, 0],
[1, 2, 3, 2],
[0, 2, 0, 7]
]
print_matrix(matrix4x3_1)
print("")
matrix4x3_2 = [
[2, 2, 8, 1],
[5, 4, 8, 2],
[5, 4, 8, 3]
]
print_matrix(matrix4x3_2)
res_matrix = []
for idx1 in range(len(matrix4x3_1)):
row = []
for idx2 in range(len(matrix4x3_1[idx1])):
row.append(matrix4x3_1[idx1][idx2] + matrix4x3_2[idx1][idx2])
res_matrix.append(row)
print("")
print_matrix(res_matrix)
print("")
# * operator for lists
print("* operator")
mul_op = ["one", "two", "three"]
print(mul_op)
mul_op = mul_op * 4
print(mul_op)
# list slice
print("\n slices")
slice_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(slice_list)
slice_list = slice_list[3:8]
print(slice_list)
# += operator
print("\n+= operator")
plus_op = [1, 2, 3, 4, 5]
print(plus_op)
plus_op += [0, 9, 8, 7, 6]
print(plus_op)
# filter
print("\n filtering")
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(nums)
filtered = list(filter(lambda x: x % 2 == 0, nums))
print(filtered)
# legal but wrong
print("\nlegal operation that does the 'wrong' thing")
legal_list = [1, 2, 3]
print(legal_list)
legal_list = legal_list.append(4)
print(legal_lis
Comments
Leave a comment