List has many operations to perform. The basic operations like creating a list, changing a value, displaying a list, searching an element in a list and finding length of a variable is explained in part 1.
https://www.blogger.com/blog/post/edit/5251857942821229/7649420483850529537
In part 2, the remaining operations are listed below.
- Adding a value
- Removing a value
- Empty a list
- Usage of constructor
The operations are explained below.
=>Adding a value:
This can be achieved by two ways. First one is adding a value in the end of the list. Second one deals with adding in a specified index.
Method1:Adding a value in the end of the list:
colorlist=["Red", "Green", "Yellow" ]
colorlist.append( "Orange")
print(colorlist)
While executing this code, you get the following output.
[ 'Red', 'Green', 'Yellow', 'Orange' ]
Method2: Adding an item at a specified index:
colorlist=["Red", "Green", "Yellow" ]
colorlist.insert( 1,"Orange")
print(colorlist)
The output is
[ 'Red', 'Orange', 'Green', 'Yellow' ]
=>Removing a value:
When you want to delete an item, there are two method.Either ,you can delete the last item or you can delete a specified item.
Method1 : Remove last item:
colorlist=["Red", "Green", "Yellow" ]
colorlist.pop()
It displays the output as : ['Yellow']
Method2 : Remove a item by specified value:
colorlist= ["Red" ,"Yellow", "Green"]
colorlist.remove("Yellow")
print(colorlist)
The output is : ['Red' ,' Green' ]
Method3: Remove a item by index value:
colorlist= ["Red" ,"Yellow", "Green"]
del colorlist[0]
it displays [ 'Yellow', 'Green' ]
=> Empty a list:
When you want to clear the data in the list, use the following code.
colorlist = ["Red", "Yellow", "Green"]
colorlist.clear()
print(colorlist)
It clears all data in the list and prints [].
=> Usage of constructor:
Constructor is a simple method to initialize an object.
colorlist= list(("Red","Green", "Yellow" ))
print(colorlist)
The output is ['Red' ,'Green', 'Yellow']
These are second level of list operations in python.
No comments:
Post a Comment