Python List examples. Python add to list.

Python List examples. Python add to list.

As we all know arrays are very often used in every languages. Most of the languages use arrays to store values and do operations. The reason for using is ease to use and understand them. In Python we have List which are same as arrays in others languages. Today we will learn about python list and their uses with examples.

How to create a Python List?
You can create a list by just name a list and initialise with values.
>>> hostlist = ["Humpty", "Dumpty", "climb", "on", "the", "hill"]
>>> hostlist
['Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill']
Lists in python are also zero indexed alike arrays. which means you access every element individually just like in arrays
>>> hostlist[0]
'Humpty'
>>> hostlist[4]
'the'
To access values from right side of the list
>>> hostlist[-1]
'hill'
How to add element in a Python List?

You can add an element in the list by using insert, append and extend.

>>> hostlist.insert(0,"Once")
>>> hostlist
['Once', 'Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill']
>>> hostlist.append(["water", "well"])
>>> hostlist
['Once', 'Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill', ["water", "well"]]
>>> hostlist.extend(["to", "fetch", "some"])
>>> hostlist
['Once', 'Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill', ["water", "well"], 'to', 'fetch', 'some']
How to slice elements from a Python List?

>>> hostlist[2:5]
['Dumpty', 'climb', 'on', 'the']
How to search elements from python list?

>>> hostlist.index("on")
4
To check wheteher an element is present in the list or not:
>>> "hill" in hostlist
True
How to delete elements from python list?

>>> hostlist.remove("some")
>>> hostlist
['Once', 'Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill', ["water", "well"], 'to', 'fetch']
To delete the last element of the list:
>>> hostlist.pop()
>>> hostlist
['Once', 'Humpty', 'Dumpty', 'climb', 'on', 'the', 'hill', ["water", "well"], 'to']
Author
bhawanisingh
Views
1,904
First release
Last update
Rating
0.00 star(s) 0 ratings
Top