Python Search List Tutorial

Last Updated Dec 29, 2016, 07:00:14 PM





Python Search List Tutorial

Python lists are used to add, search elements in a list, just like a tree we can add new items or remove the existing items from the list

Below is an example python list


  	fruits_list = ["banana", "apple", "mango", "orange"] 
  


Every python list has few options to work with such as searching elements in the list, adding new elements, removing existing elements, sorting elements in the python list



Insert

Insert method insert() can be called on any existing python list to add or insert more elements


	my_list = [2,4,6]  # Existing list with three elements
	my_list.insert(3, "8") # Insert element "8" at third position
	my_list

Example

NOTE: The list index counting starts from ZERO. For example in the above code example-- Index of element 2 is 0, index of element 4 is 1, and index of element 6 is 3

Len

Len method can be called on any existing empty or non-empty python list to count the number of elements inside


fruits = ["banana","apple", "orange", "mango"] # An existing list with 4 elements inside
my_other_list = [] # An existing list with zero elements

# Calculating the count of elements in two lists
size_of_fruits_list = len(fruits)
size_of_my_other_list = len(my_other_list)

print("No of elements in fruits list is:", size_of_fruits_list)
print("No of elements in my_other_list is:", size_of_my_other_list)

Example

Remove

Remove method remove() can be called to delete/remove any matching element in a list. It takes an argument as value and it verifies against that value, if the value matches in the list it removes that matched element.



fruits = ["mango", "banana", "apple", "orange"]
print("Before calling remove method:", fruits) 

fruits.remove("banana") # Remove banana from the list

print("After calling remove method:", fruits)

Example

Del

Python del() method is used to delete a specific element from the list by calling it's index


fruits = ["mango", "banana", "apple", "orange"]

print ("Before deleting ")
print(fruits)

del fruits[1] # Delete element at index 1
print("after deleting")
print (fruits)

Example

Append

Python append() method can be called on any empty or non-empty list to add/append new elements


my_list = [50]  # An empty list

print("Before appending:", my_list)
my_list.append(100)
my_list.append(200)
my_list.append(300)

# Three new elements 100, 200, 300 are appended to the list
print("After appending:", my_list)

Example

Extend

Extend method extend() is used to to extend the existing list by joining other list


# Two lists.
a = [2, 4, 6]
b = [8, 10, 12]

# Add all elements in list "b" to list "a."
a.extend(b)

# List "a" now contains six elements.
print(a)

Example

Sort

Sort method sort () is used to sort all the items in the list


my_list = [4,7,2,9,5,1,3,6]  # Unsorted list items
print("Before sorting:", my_list)
my_list.sort()
print("After sorting:", my_list)




.