Saturday, 13 February 2016

How to use Lists in Python - A close look

Today I am going to deal with lists in Python. Here I will dive into the details of lists covering how to use them . I will try to show you each way with code describing it in detail.
What is a List in Python?
 Lists in general is a data-structure which can hold a particular type of elements and its size can increase or decrease. But a List in Python is quite different. It is a built-in data type which can hold multiple types of elements - numbers, strings, tuples, lists, dictionaries.So this is the beauty of lists in Python.
How to declare a List in Python?
It is very easy to declare and initialize a list in Python. I will show how to create an empty list, list with similar type of elements and list with different type of elements.
It is done just by using brackets as shown below
x = []   #Empty list created
x = [1,2,3,4,5] #list with 5 elements
x = ["one",2,3.0,(4,5),[6,7,8]]   #list with different types of elements

How to access elements in a listin Python?
Elements in a list can be accessed in a similar fashion to arrays in other languages like C, Java. You can access elements using indices. But here is a twist. You can access elements using both positive and negative indices. Positive index works similar to arrays while negative indices works with index of last element in list as -1 and index increases as it gradually moves to the beginning of the list. You can alsoslice a portion of the list using [m:n] structure. When you write this, it slices a portion of the list with elements from m till index n-1.If you write [m:], it extracts elements from m till the end. If you write [:n], it will slice list and form elements starting from beginning till n-1th element. 
x = [10,20,30,40,50]   #list with 5 elements
x[0]   #output = 10
x[3]   #output = 40
x[-1]   #output = 50
x[-3]   #output = 30
x[1:4]   #output = [20,30,40]
x[1:-1]   #output = [20,30,40]
x[-4:-2]   #output = [20,30]

How to modify/increase or decrease size of list?
You can replace a portion of the list with a new set of elements. If the number of new set of elements is greater than the numbers of elements it is replacing, then the size of list increases otherwise decreases. You can also use operators like + and * with lists. But remember that it does not change the original list on using these operators. It is shown below
x = [1,"two",3.0,4,5,6]
x[5:6] = []   #output = [1,"two",3,4,5] list size decreases
x[2:4] = [3.0,3.5,4.0]   #output = [1,"two",3.0,3.5,4.0,5]
[-1,0] + x   #output = [-1,0,1,"two",3.0,3.5,4.0,5]

How to use functions with list?
You can use functions with list.  Most important function is len() which returns the length of the list. min() returns minimum value while max() returns maximum element. reverse() reverses the elements in a list.

No comments:

Post a Comment