1. insert()
The insert() method is used to insert a new item into a particular position in the list.
Syntax:
The insert() method contains two arguments. The first argument takes the position value where the new item will be inserted. The second argument takes the new item value.
Example:
In the following script, a list variable with 7 items is declared. Next, the insert() method is used to insert the new item, ‘Processor’ at position 1. The list is printed before and after inserting the new item.
# Define a list of string
Listdata = ['HDD', 'motherboard', 'Printer', 'Scanner', 'Mouse', 'Keyboard','RAM']
# print the list
print("\nThe list before insert:\n", Listdata)
# Insert a new item in the list
Listdata.insert(1,'Processor')
# print the list after insert
print("\nThe list after insert:\n", Listdata)
Output:
The following output will appear after running the script from spyder. The original list and the list after performing the insert() method are printed here.
2. append()
The append() method is used to insert a new item at the end of the list.
Syntax:
This method takes the new value as an argument that will be inserted at the end of the list.
Example:
In the following script, a list named stdList is declared with different types of data containing string and number values. Next, the append() method is used to insert a floating number at the end of the list. The list is printed before and after appending the new data.
# Define a list
stdList = ['Mir Subbir', 'CSE', 46, 9]
# print the list
print("\nThe list before append:\n", stdList)
# Append a new item in the list
stdList.append(3.85)
# print the list after append
print("\nThe list after append:\n", stdList)
Output:
The following output will appear after running the script from spyder. The original list and the list after performing the ()append method are printed here.
3. remove()
The remove() method is used to remove a particular item from the list.
Syntax:
This method takes the item value as an argument that will be removed from the list, if it exists. If the item value does not exist in the list, then a ValueError will be generated.
Example:
A list of 6 string values is defined in the following script. Next, a string value will be taken as the input to be searched for and removed from the list. The capitalize() method is used in the script to match the input value with the list item, where the first character of each item is capitalized. The list will be printed before and after removing the item from the list. The try-except block is used, here, to handle the ValueError response.
# Define a list of fruit names
listdata = ['Mango', 'Banana', 'Orange', 'grape', 'Guava', 'Watermelon']
# Print the list
print("List before remove:\n", listdata)
remove_item = input("Enter the fruit name to remove:")
try:
# Remove a item from the list if exist
listdata.remove(remove_item.capitalize())
# Print the list after remove
print("\nList after remove:\n", listdata)
except ValueError:
print("Item does not exist in the list")
Output:
After running the script, the list will print and ask for the user input. ‘Guava’ is taken as the input that exists in the list. This value is removed from the list and the modified list is then printed.
4. extend()
The extend() method is used to merge two list items and store the merged items in the first list.
Syntax:
This method takes the second list as the argument and adds the values of the second list at the end of the first list.
Example:
Two lists, named clientList1 and clientList2, are declared in the following script. Next, the extend() method is used to insert the values of clientList2 at the end of clientList1. Then, clientList1 will print after inserting the items.
# Define two list of client names
clientList1 = ['John','Ella','Micheal','Watson']
clientList2 = ['Abir','Nahar','Zafar']
# Insert the items of the second at the end of first list
clientList1.extend(clientList2)
# Print the first list after extend
print("The output after extend:\n", clientList1)
Output:
The following output will appear after running the script from spyder. The list with extended values will print.
5. count()
The count() method is used to count the number times that any given item appears in a list.
Syntax:
This method takes the item value as an argument that will be searched for in the list and returns the number of the appearances of the item in the list as a numerical value. If the item value does not exist in the list, then it will return with the value 0.
Example:
In the following script, a list variable of numeric data is declared. After printing the list, a numerical value will be taken as the input that will be searched in the list. If the input number exists in the list one or more times, then it will return the total number of the appearances of the searched item; otherwise, if the input number does not exist in the list, it will return a 0.
# Define a list of numbers
listdata = [12, 23, 5, 27, 45, 5, 56, 6, 65]
# Print the list
print("The list content:\n", listdata)
# Take any numeric data
search_item = int(input("Enter any number to search:"))
print("The %d appears %d times in the list" %(search_item,listdata.count(search_item)))
Output:
After running the script the list is printed. The user will be asked for a user input that will be searched in the list. 5 is taken as the input; the output shows that this input appeared 2 times in the list. The script is executed for the second time and 89 is given as the input that does not exist in the list. So, the count() method returns 0.
6. index()
The index() method is used to obtain the position value of any item in the list.
Syntax:
This method takes the search item value as the input and returns with the position value of the item in the list, if it exists; otherwise, it generates a ValueError.
Example:
A list of string values is declared in the following script. After printing the list values, a string value will be taken as the input. The input value will be searched in the list with the index() method. If the value exists in the list, then the position value of the input string will be returned; otherwise, a custom error message will print.
# Define a list of numbers
listdata = ['John','Ella','Micheal','Watson','Meher']
# Print the list
print("The list content:\n", listdata)
# Take any numeric data
search_item = input("Enter any name to search:")
try:
print("The %s is found at position %d in the list"
%(search_item,listdata.index(search_item.capitalize())+1))
except ValueError:
print("The item does not exist in the list.")
Output:
After running the script, the content of the list is printed and the method asks for an input value to search for in the list. ‘Watson’ is taken as the input that exists in position 4 of the list, as shown in the formatted output. Next, ‘Jolly’ is taken as the input that does not exist in the list, generating a ValueError that prints from the except block.
7. copy()
The copy() method is used to make a copy of a list. This method is useful for keeping original list values before modifying the list.
Syntax:
This method does not take any argument as an input, it just creates a duplicate copy of the list.
Example:
In the following script, two lists, named clientList1 and clientList2, are declared. Before changing the content of clientList2, the copy() method is used to make a copy of clientList2 and store the list values in another variable, named originalList2. Next, the extend() method is used to add the content of clientList1 at the end of clientList2. The previous content and the merged content of clientList2 are then printed.
# Define two list of client names
clientList1 = ['John','Ella','Micheal','Watson']
clientList2 = ['Abir','Nahar','Zafar']
# Make a copy of clientList2
originalList2 = clientList2.copy()
# Insert the items of the first list at the end of second list
clientList2.extend(clientList1)
# Print the values of clientList2 before extend
print("The original values of clientList2 is:\n", originalList2)
# Print the values of clientList2 after extend
print("The output after extending clientList2:\n", clientList2)
Output:
The following output will appear after running the script from spyder. The original and merged list values are printed below.
8. sort()
The sort() method is used to sort list data. This method is useful when you are working with the same type of list data and you need to organize the data for any programming purpose.
Syntax:
This method does not take any argument and it returns the sorted list data in ascending order.
Example:
A list of numeric data is defined in the following script. The list is printed before and after applying the sort() method.
# Define a list of numbers
listdata = [12, 23, 27, 45, 5, 56, 6, 65]
# Print the list
print("The list before sort:\n", listdata)
# Sort the list
listdata.sort()
# Print the list after sort
print("The list after sort:\n", listdata)
Output:
The following output will appear after running the script from spyder. The original list and sorted list in ascending order are printed.
9. reverse()
The reverse() method is used to reverse the items in any list. This method is useful for sorting lists in descending order.
Syntax:
This method does not take any argument and it returns the list items in reverse order.
Example:
The following script shows how to sort a list of numeric data in descending order. A list of numeric data is defined. The list is printed before sorting. Next, the sort() method is used to sort the list in ascending order. The reverse() method is then used to organize the list in descending order.
# Define a list of numbers
listdata = [120, 4, 78, 5, 50, 21, 56, 9]
# Print the list
print("The list before sort:\n", listdata)
# Sort the list
listdata.sort()
# Reverse the list
listdata.reverse()
# Print the list in descending order
print("The list after sort and reverse:\n", listdata)
Output:
The following output will appear after running the script from spyder. Here, the original list and sorted list in descending will print.
10. clear()
The clear() method is used to remove all the items in a list and to empty lists. This method is useful for re-assigning the values of a list by removing the previous items.
Syntax:
This method does not take any argument as input and it returns an empty list.
Example:
The following script shows how to use the clear() method. A list of string values is declared and printed at the beginning of the script. Next, the clear() method is used to remove all items in the list and to print the empty list.
# Define a list
deptList = ['CSE','English','BBA', 'Pharmacy','Math' ]
# print the list
print("\nThe list content:\n", deptList)
# Clear the list
deptList.clear()
# print the list after clear
print("\nThe list after clear:\n", deptList)
Output:
The following output will appear after running the script from spyder. At first, the list values are printed and next the empty list is printed.
Conclusion
This article described the ten most useful and popular list methods in Python, as well as the uses of each of these list methods.
from Linux Hint https://ift.tt/2NzmabM
0 Comments