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]
>>> hostlist[4]
To access values from right side of the list
>>> hostlist[-1]
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")
To check wheteher an element is present in the list or not:
>>> "hill" in hostlist
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']
First release
Last update
0.00 star(s) 0 ratings