List in python programming language are used to hold or group collection of data in an ordered way. If you want to group some similar data than you can use list to do so. List is created using the square bracker [ ]. Following is an example of a list in python.

L = ['jon', 20, 1000]

The first element is a string called jon. It index position is at 0. That is list indexing starts with 0. Matlab index position starts with 1. Then we have two integers 20 and 1000.

The syntax of python list is like array in other programming languages such as c, C++, matlab etc.

To get or refer to the first element we use the indexing operation using the square bracket. 

L[0]
'jon'

L[1]
20

and L[2] is
1000

Remember that list in python are ordered. That is the elements of list have fixed positional index. This is unlike dictionary which uses curly braces { } which are unordered list.

Python list can hold any kinds of different data types within the same list like integer, float, strings, another list and dictionaries etc. The above example showed you that it can hold a string like person name like jon and integers data type like 20 and 1000. The string and integers are themselves objects called string object and integer object. Everything in python programming language are objects.

Once list is created you can add new items to the list, delete items from the list, insert items anywhere in position in the list and so on. Following are some examples for these things.

Appending item to a list:

L.append(2000)

L
['jon', 20, 1000, 2000]

Using the append method on the list object L we can append another item like 2000. You can add any data type.

Deleting item from a list:

If you want to delete the e=item just added which is 2000 at position 3 then you can use the del command as follows.

del L[3]

L
['jon', 20, 1000]

Inserting items to a list:

If you want to insert item not in the last position but anywhere in between the items of a list then you can use the insert method as follows.

L.insert(1,'smith')

L
['jon', 'smith', 20, 1000]

Find out index number of an item in a List:

Using the index method you can find out what is the index number of an item.

L.index(20)
2

Check item in a list or not:

If you want to check whether a given item is in a list or not you can use the is keyword as follows.

20 in L
True



0 comments:

Post a Comment

 
Top