Python Lists Create

In Python, the list is a ordered collection. Duplicate members can be added to the lists and it changes. One wonderful thing about Python lists is that it can be created by items of different types.

Inside a list collection, you can add new members even during run time. All the elements added to the lists are objects. The other list can also be added as a member inside a list. Such lists are called sublists or nested lists.

Python List Create

The lists in Python are defined by square brackets. For example, look at the given code below.

myList = ["bike","skooti","Car"]
print (myList)

In the above example a list collection has been created by the name of myList, in which the bike, skooti and car strings have been added respectively. Later this list has been printed by the print statement.

In Python, you can define a list collection in another way in which the list () constructor is used. To define list by list constructor, members inside the list () constructor are passed.

Round brackets are used instead of square brackets to define members, and they are defined as the comma separated list inside the list () constructor.

For example, look at the given code below.

myList = list(("bike","skooti","car"))
print(myList)

Functions and Methods of Python List

All methods are called by list object and functions are called independently.

append ()
The append () method is used to add any new item to the list. As an argument inside this method, you pass the item that you want to add to the list. An example of this is being given below.

myListpython = list(("bike","skooti","car"))
print(myListpython)
myListpython.append("bus")
print(myListpython)

len ()
The len () function is used to find the length of any list, how many items are there in it. This function is passed to the list in the form of a argument. An example of this is being given below.

myListpython = list(("bike","skooti","car"))
print(len(myListpython))

remove ()
The remove () method is used to remove any existing item from the list. In this method, in the form of argument, you pass the item that you want to remove from the list. An example of this is being given below.

myListpython = list(("bike","skooti","car"))
print(myListpython)
myListpython.remove("bus")
print(myListpython)

 

clear ()
This function is used to remove all elements from a list. From this the list is empty.

myListpython = list(("bike","skooti","car"))
print(myListpython)
myListpython.clear()
print(myListpython)

sort ()
This method can be sorted by a list.

myListpython = list((1,2,4,3))
print (myListpython.sort())

 

count ()
Like the len () function, count () method is also available to tell the number of members in the list. You call it with the string object.

myListpython = list(("bike","skooti","car"))
print (myListpython.count())