Sunday, October 25, 2020

Operations on Python Lists

An empty python list is created using empty square braces with the following syntax list5=[], here an empty list list5 is created.

Inserting an Element to Python List:

Element is inserted into the list using the insert function. It takes two arguments index and element.
list.insert(index,element)

insert function can also be used to insert an element at particular position, now we insert O into fourth position to make the string python.

Appending an Element to Python List:
To append an element to the list use append function. It takes one argument.
list.append(element)
append function always adds element to the end of the current list. Here we inserted a space followed by PRO.
To append a new list to the current list use the extend function. It takes list as an argument 
list.extend(newList)
In the above example a new list list6 is added to list5.

Replacing an Element in Python List:
To replace element with a new value in python is done by assigning a new value at corresponding index
location.
Here element at position 0 is replaced by J. string has converted from "PYTHON PROGRAMMING" to "JYTHON PROGRAMMING" . Similarly all other elements can be replaced.

Removing an Element from Python List:
Removing or deleting an element from python lists using remove function. remove function takes element as an argument to be removed.
list5.remove(element)
The element to be removed is present multiple times in a list, only the first occurrence is removed.
 
To delete an item from python we use del keyword. del can be used to delete a 
single element : del list5[0] , del list5[-1] 
multiple elements : del list5[2:5]
and also entire list : del list5 


count:
Count returns number of occurrences of that element in a list. 


pop:
pop function takes a single argument that is index. pop removes the item at the given index. 
pop index defaults to -1 when no index is passed to pop function. 
pop returns a value and its the popped item form the list.


reverse:
reverse function updates the list elements in the reverse order.
list.reverse()

Elements of animals are displayed in the reverse order after the reverse function.

sort:
sort function is used to sort the elements in the ascending order of items in the list.

After the sort operation on animals list, items of the list are sorted in ascending order. 
clear:
Clear functions clears all the elements present inside the list.












No comments:

Post a Comment

Operations on Python Dictionaries