Sunday, July 24, 2022

What are the basic list operations?

List operations are very important since they give us the ability to manipulate them. These operations allow us to add list elements to existing lists, slice the list, extend lists, delete list elements, add two lists, multiply two lists, subtract two lists, divide two lists, and transform strings to a list and vice versa.

How to add list elements?

Two operations can be used to add list elements using functions append and extend. The append function is usually used to append elements to an empty list or to append elements to an existing list. The append list will add new elements to the end of a list. The general form of append function can be written as:
list_name.append(value)
To append any value to a list first you need to write a variable that contains a list (list_name) then type a dot (.) and then write the append() function with the value inside the brackets. The value can be any type (integer, float, character, string,...). Example 1 Create a empty list and append numbers from 0 to 5 (including 5) to the list. Then append 3 arbitrary numbers to the list (using the append function).
Solution:To create empty list "ListA" simply use the built in function list().
ListA = list()
Now we will use the for loop and append function to append numbers from 0 to 5 (including 5) to ListA.
for i in range(0,6,1):
ListA.append(i)
To show what we have done with previous code we will traverse over ListA and using the print function show every element of a list.
for i in range(len(ListA)):
print("ListA[{}] = {}".format(i, ListA[i]))
This will generate the following output.
ListA[0] = 0
ListA[1] = 1
ListA[2] = 2
ListA[3] = 3
ListA[4] = 4
ListA[5] = 5
Now we will add three arbitrary chosen numbers with the append function. The numbers are 345, 456, and 567.
ListA.append(345)
ListA.append(456)
ListA.append(567)
And to show all list elements we will use the same code for printing out the list elements as before. The output is given below.
ListA[0] = 0
ListA[1] = 1
ListA[2] = 2
ListA[3] = 3
ListA[4] = 4
ListA[5] = 5
ListA[6] = 345
ListA[7] = 456
ListA[8] = 567
In the next example, we will utilize the extend function to extend the list with elements from another list. The extend function takes a list as an argument and appends all of the elements. The general form of extending function usage can be written as:
list_name1.extend(list_name2)
where list_name1 is the first list that we want to extend using the extend function with elements from list_name2 i.e. the second list. The list_name2 is the argument of the extended function. Exampel 2 Create two lists and using extend function extends the first list with elements from the second list.
Solution:First the list L1 will be created with numbers 50 to 60 (including 60) and the second list from 100 to 105 (including 105).
L1 = [i for i in range(50,61,1)]
L2 = [i for i in range(100,106,1)]
We will simply show two lists using the print function.
print("L1 = {}".format(L1))
print("L2 = {}".format(L2))
This will generate the following output.
L1 = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60]
L2 = [100, 101, 102, 103, 104, 105]
Now we will use the extend function to add elements of L2 to the list L1.
L1.extend(L2)
To see the L1 list type in the following.
print("L1 = {}".format(L1))
which will generate the following output.
L1 = [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 100, 101, 102, 103, 104, 105]
The sort function will arrange elements in the list from low to high. The general form of sort function implementation can be written as:
list_name.sort()
where list_name is the list name that we want to sort and sort() function that sorts list elements. The brackets of the sort function are empty. In the following example, we will use the sort function for sorting numbers from lowest to highest. Example 3 Create a list with 5 user-defined numbers and then apply the sort function to sort the list elements from lowest to highest.
Solution: First we are going to create list L1 and print out the entire list.
L1 = [365, 123, 325, -23, 415]
print("L1 = {}".format(L1))
This will generate the following output.
L1 = [365, 123, 325, -23, 415]
Now we will apply the sort function to the L1 list and print out the result.
L1.sort()
print("L1 = {}".format(L1))
Which will generate the following output.
L1 = [-23, 123, 325, 365, 415]
This can be done with characters also and is shown in Example 4. Example 4 Sort the list ['e', 'a', 'c', 'z'] using sort function.
Solution:
Str1 = ['e', 'a', 'c', 'z']
Str1.sort()
print("Str1 = {}".format(Str1))
The output is given below.
Str1 = ['a', 'c', 'e', 'z']

How to delete list elements?

There are several ways how to remove list elements. The elements can be removed from the list using the pop, remove, and del function. The pop function is used when you know the index of the element you want to remove from the list. The general form of using the pop function on a list element can be written as:
list_name.pop(index)
After list_name is a dot and after dot a function pop with the index number of the list element. The pop function modifies the list and returns the element that was removed. If the index of the list element is not provided as an argument of the pop function then the function will delete the last element in the list.
Example pop_1 Create a list of 5 elements and pop the second element in the list and then use the pop to delete the last element in the list. Throughout these steps use print to show the current form of a list.
Solution:We will create list with five numbers from 45 to 50. Then we will show the list using the print function.
LstA = [i for i in range(45,50,1)]
print("LstA = {}".format(LstA))
This will generate the following output.
LstA = [45, 46, 47, 48, 49]
Since the pop function removes a specific element if the index is provided as an argument of the pop function and returns the element that was removed we have to create a new variable (x) and the value will be assigned to this variable.
x = LstA.pop(1)
print("LstA = {}".format(LstA))
print("x = {}".format(x))
This will generate the following output.
LstA = [45, 47, 48, 49]
x = 46
So we used to pop to remove the second element from the list or the element located at index 1 which was 46. Using the pop function this number (46) was assigned to a variable x. Now we will use pop to remove the last element in the list. This will be done by using pop without any function argument.
y = LstA.pop()
print("LstA = {}".format(LstA))
print("y = {}".format(y))
This will generate the following output.
LstA = [45, 47, 48]
y = 49
As you can see the pop function will remove the last element in the list if the pop function is specified without any argument. The value that was removed from the list (number 49) and was saved under variable y.
If you know the element you want to remove but not the index then it is good to use the remove function. The general form of the remove function applied to a list can be written as:
list_name.remove(list_element)
After list_name you have to write. and then remove the function with the value of list_element as an argument. The remove function does not have a return value i.e. the return value is None. In the next example, the remove function will be used.
Example xx-Remove Create list with 5 characters and using remove function remove characters 'b' and 'd'. After each step writes the print function to see what is changed in the list.
Solution: The list consist of elements 'a', 'b', 'c', 'd', 'e'.
ListR = ['a', 'b', 'c', 'd', 'e']
print("ListR = {}".format(ListR))
ListR.remove('b')
print("ListR = {}".form(ListR))
ListR.remove('d')
print("ListR = {}".format(ListR))
The previous block of code will generate the following output.
ListR = ['a', 'b','c', 'd', 'e']
ListR = ['a', 'c', 'd', 'e']
ListR = ['a', 'c', 'e']
Ok so first we have created ListR with elements 'a','b','c','d', and 'e'. After we have created ListR we used the print function to print out ListR. Then we used the remove function and remove 'b' element and again print out the ListR. Finally, the element 'd' is removed from the list using the remove function and again the list is printed out.
If you want to remove more than one element use the del function. The general form of using the del function can be written as:
del list_name[start_index:end_index]
After the del function the list_name must be specified i.e. the list on which we are going to use the del function. After that in square brackets, we have to specify the first index (starting index) and last index of an element but not include one.
Example xx-del Create a list with 10 numbers and use del function to delete 5 elements.
Solution:
numbers = [i for i in range(0,10,1)]
print("numbers = {}".format(numbers))
del numbers[1:6]
print("numbers = {}".format(numbers))
This will generate the following output.
numbers = [0,1,2,3,4,5,6,7,8,9]
numbers = [0,6,7,8,9]

What built-in functions can be used on lists ?

There are several built-in functions that could be used on lists and these are:
  • sum() - calculates the sum of all list elements. This function only works when a list contains numbers.
  • max() - this function searches for maximum value in the list.
  • min() - this function searches for minimum value in the list
  • len() - calculates the length of a list.
Example 1 Create a list with 5 arbitrary chosen numbers and apply previously mentioned functions.
Solution: The list of 5 arbitrary chosen numbers.
List1 = [2,10,22,36,43]
The sum function will add all numbers to the list. To show the result we will use the print function.
print("sum(List1) = {}".format(sum(List1)))
Which will generate the following output.
sum(List1) = 113
The max function will search the list for the maximum value and retrieve it. To show the max value of the List1 we will use the print function.
print("max(List1) = {}".format(max(List1)))
The output is shown below.
max(List1) = 43
The min function will search for the minimum value in the list and retrieve it. To show the min value of the List1 we will use the print function.
print("min(List1) = {}".format(min(List1)))
The output is given below.
min(List1) = 2
The length function will give the length value of the list.
print("len(List1) = {}".format(len(List1)))
The output is given below.
len(List1) = 5
Example 2 Write the program that will ask the user to write each member of the list and calculate the sum, minimum, maximum, and average value of the generated list.
Solution: In this example we need an "input" function that will ask a user of a program to define each element of the list. We need a specific word that will end the manual entering list elements. This will be a "quit" word. Of course, we need to create an empty list and fill it in each iteration with a number provided by the user (note: list filled with append function). The entire code is given below.
List1 = []
while True:
USER_INPUT = input("Enter a number (type quit if you're done creating list): ")
if USER_INPUT == "quit": break
List1.append(float(USER_INPUT))
print("List1 = {}".format(List1))
print("sum(List1) = {}".format(sum(List1)))
print("max(List1) = {}".format(max(List1)))
print("min(List1) = {}".format(min(List1)))
print("len(List1) = {}".format(len(List1)))
print("sum(List1)/len(List1) = {}".format(sum(List1)/len(List1)))
The program starts with creating the empty list under the variable name "List1". Then in the while loop under the USER_INPUT variable, the value entered by the user is saved. If the user types "quit" it will terminate the while loop. The entered USER_INPUT will be converted to the float type and appended in List1. After the user is done entering the list elements the program will start executing the print functions. Using the print function the output shown will be List1, the sum of the List1, max in List1, min of List1, length of List1, and the average of List1 (sum(List1)/len(List1)). The example of the output for a list of 4 elements is shown below.
Enter a number (type quit if you're done creating list): 15
Enter a number (type quit if you're done creating list): 14
Enter a number (type quit if you're done creating list): 2
Enter a number (type quit if you're done creating list): 3.5
Enter a number (type quit if you're done creating list): quitList1 = [15.0, 14.0, 2.0, 3.5]
sum(List1) = 34.5
max(List1) = 15.0
min(List1) = 2.0
len(List1) = 5
sum(List1)/len(List1) = 8.625

No comments:

Post a Comment