In the previous post, I have covered the basics of Python lists. Here, I am going to give some more information about lists in Python.
Changing Items in a List
Like I had written in my previous post, list items are changeable. Here is a simple program to change an element in a list;
list=["red","yellow","green"] list[0]=blue print(list)
Output:
In the above code, the element with index number 0 i.e. "red" is changed to "blue".
Changing a range of elements
We can change a range of elements of a list too by using the following program-
list=["apple","banana","mango","litchi","grapes"] list[1:3]=["blueberry","strawberry"] print(list)
Output:
If you insert more items that the number in the range specified, the extra item(s) will be placed at the index number specified and the other items will move accordingly and the length of the list will change. For example;
list=["red","green","blue","yellow"] list[1:2]=["orange","black"] print(list)
Output:
Inserting a new element
To insert a new element in a list, we can use the insert() method. For example;
list=["red","green","blue"] list.insert(1,"white") print(list)
Output:
In the above code, in the insert() method, we first give the index number where we want the element to be added and then give the input. Here, the index number is 1 so, "white" will be added as the second element.
Adding an item to the end of the list
We can add an item to the end of the list by using the append() method. For example;
list=["red","green","yellow"] list.append("blue") print(list)Output:
Extending a list
A list can be extended by using the extent() method.For example;
list1=["red","green","blue"] list2=["white","black"] list1.extend(list2) print(list1)
Output:
Removing items from a list
Removing specified items from a list
We can remova a specified item from a list using the remove() method. For example;
list=["red","green","blue"] list.remove("green") print(list)
Output:
Removing elements by their index number
We can remove elements by their index number by using the pop() method. For example;
list=["red","green","blue"] list.pop(0) print(list)
Output:
In the above code, the element with the index number 0 i.e. "red" is removed.
Deleting the entire list
The entire list can be deleted by using the del keyword. For example;
list=["red","green","blue"] del list print(list)
The output will tell error because 'list' has successfully been deleted and you can't print it.
Clearing the list
You can clear the list by using the clear() method. For example;
list=["red","green","blue"] list.clear() print(list)
Output:
That is all for this post on Python Lists. Hope you found it informative and easy to understand.
Check out my account on Medium!
Regards,
Aarav Iyer