Lab Activities - List Practice in Python
2.9.1 Let's Practice How to Create Different Types of Lists
# Create an empty list and store it in a variable called list1
list1 = []
# Create a variable named list2 and initialize that list with numbers 1, 3, 4, 3, 5
list2 = [1, 3, 4, 3, 5]
# Create a variable named list3 and initialize that list with elements 23, 'Hi', 4.5
list3 = [23, 'Hi', 4.5]
# Create a variable named list4 and initialize that list with variables a and b
a = 10
b = 20
list4 = [a, b]
# Print all the lists created above
print(list1)
print(list2)
print(list3)
print(list4)
2.9.2 Let's Practice List Slicing Concepts
# Create a list of stationery with elements pen, pencil, eraser, sharpener, and ruler
stationery = ['pen', 'pencil', 'eraser', 'sharpener', 'ruler']
# Print the second element of the stationery list
print(stationery[1])
# Print the last element of the stationery list
print(stationery[-1])
# Print the first element of the stationery list with list indexing
print(stationery[0])
# Print the second last element of the stationery list with the negative index
print(stationery[-2])
2.9.3 Let's Practice List Manipulation by Doing Addition of Elements in the List
# Create a numbers list with values 1, 2, 3
list_numbers = [1, 2, 3]
# Add 4 at the end of the list numbers using the append() method
list_numbers.append(4)
# Add numbers 5 to 10 using a loop and append method
for i in range(5, 11):
list_numbers.append(i)
# Append i variable of for loop in every iteration
# (Already done above in the same loop)
# Use extend() to add the list containing elements 11, 12 and 13
list_numbers.extend([11, 12, 13])
# Use insert() to add number 14 at the index number 2
list_numbers.insert(2, 14)
# Print the updated list
print(list_numbers)
2.9.4 Let's Practice List Manipulation by Doing Deletion in the List
# Create a list with variable name List, giving it values 1 to 12
List = list(range(1, 13))
# Print List
print(List)
# Remove 5 from the list using remove()
List.remove(5)
# Write a for loop with a range 1 to 5 and remove the first five numbers from the List
for i in range(1, 6):
if i in List:
List.remove(i)
# Print updated List
print(List)