python


Python List


Introduction to Python List

Unlike C++ or Java, Python doesn’t has arrays. So , to hold a sequence of values, Python provides us a special built in class called ‘list’ .Thus a list in Python is defined as a collection of values.The important characteristics of Python lists are as follows:
1) Lists are ordered.
2) Lists can contain any arbitrary objects.
3) List elements can be accessed by index.
4) Lists can be nested to arbitrary depth.
5) Lists are mutable.
6) Lists are dynamic.
In Python, a list is created by placing all the items (elements) inside a square bracket [ ], separated by commas. It can contain heterogeneous elements also.We also can create a list by using the list( ) function We can print a list in three ways:
1) Directly passing it to the print( ) function.
2) Accessing individual elements using subscript operator [ ].
3) Accessing multiple elements using slice operator [ : ].


mynums=[10,20,30,40,50]
print(mynums)
Output

[10,20,30,40,50]
Adding new element to a list
The most common way of adding a new element to an existing list is by calling the append( ) method.This method takes one argument and adds it at the end of the list

mynums=[10,20,30,40,50]
print(mynums)
mynums.append(60)
print(mynums)
Output

[10,20,30,40,50]
[10,20,30,40,50,60]    
Slice Operator With List
Just like we can apply slice operator with strings , similarly Python allows us to apply slice operator with lists also.
Syntax: list_var[x:y]
x denotes the start index of slicing and y denotes the end index . But Python ends slicing at y-1 index.
slicing can accept a third parameter also after the two index numbers.The third parameter is called step value.So the complete syntax of slicing operator is:
s[begin:end:step]
Step value indicates how many characters to move forward after the first character is retrieved from the string and it’s default value is 1 , but can be changed as per our choice. Another point to understand is that if step is positive or not mentioned then Movement is in forward direction ( L->R) Default for start is 0 and end is len But if step is negative , then Movement is in backward direction (R->L) Default for start is -1 and end is –(len+1) Examples:

mynums=[10,20,30,40,50]
print(mynums[1:4]) 
mynums=[10,20,30,40,50]
print(mynums[1: ])
mynums=[10,20,30, 40,50]
print(mynums[:3])
mynums=[10,20,30,40,50]
print(mynums[1:4:2])
Output

[20,30,40] 
[20,30,40,50] 
[10,20,30 ]
[20,40]


Operations on Python List

Modifying A List
Python allows us to edit/change/modify an element in a list by simply using it’s index and assigning a new value to it.
Syntax:list_var[index_no]=new_value
Python allows us to modify multiple continuous list values in a single statement , which is done using the regular slice operator.
Syntax:list_var[m:n]=[list of new value ]

sports=["cricket","hockey","football","snooker"]
print(sports)
sports[1:3]=["badminton","tennis"]
print(sports)  
Output

["cricket","hockey","football","snooker"]
["cricket","badminton","tennis","snooker"]
Deleting Item From The List
Python allows us to delete an item from the list by calling the operator/keyword called del. Syntax:del list_var[index_no]
Python allows us to delete multiple items from the list in 2 ways:
1) Assigning Empty List
2) Passing slice to del operator

sports=["cricket","hockey","football","snooker"]
print(sports)
del sports[3]
print(sports) 
Output

["cricket","hockey","football","snooker"]
["cricket","hockey","football"]
Deleting Entire List
We can delete or remove the entire list object as well as it’s reference from the memory by passing the list object reference to the del operator.
Syntax: del list_var
Appending Or Prepending Items To A List
Additional items can be added to the start or end of a list using the + concatenation operator or the += compound assignment operator The only condition is that the item to be concatenated must be a list

sports=["cricket","hockey","football"]
sports=["carrom","chess","table-tennis"]+sports
print(sports)
Output

["carrom","chess","table-tennis","cricket","hockey","football"]                  
Multiplying A List
Python allows us to multiply a list by an integer and when we do so it makes copies of list items that many number of times, while preserving the order.
Syntax: list_var * n
Membership Operator On List
We can apply membership operators in and not in on the list to search for a particular item
Syntax: element in list_var


Builtin Functions for List

There are some built-in functions in Python that we can use on lists. These are:
len(): Returns the number of items in the list
max(): Returns the greatest item present in the list
min(): Returns the least item present in the list
sum(): Returns the sum of all the items present in the list . However items must be of Numeric or boolean type
sorted(): Returns a sorted version of the list passed as argument. To sort the list in descending order , we can pass the keyword argument reverse with value set to True to the function sorted( )
list(): The list( ) function converts an iterable i.e tuple , range, set , dictionary and string to a list.
any(): The any( ) function accepts a List as argument and returns True if atleast one element of the List is True. If not, this method returns False. If the List is empty, then also it returns False
Syntax: list(iterable)
all(): The all( ) function accepts a List as argument and returns True if all the elements of the List are True or if the List is empty .If not, this method returns False.
all(iterable)


List Methods

There are some methods also in Python that we can use on lists. These are:
1)append(): Adds a single element to the end of the list . Modifies the list in place but doesn’t return anything
Syntax: list_var.append(item)
2)extend(): extend() also adds to the end of a list, but the argument is expected to be an iterable. Modifies the list in place but doesn’t return anything.
Syntax: list_var.extend(iterable)
3)insert(): The insert() method inserts the element to the list at the given index. Modifies the list in place but doesn’t return anything
Syntax: list_var.insert(index,item)
4)index(): The index() method searches an element in the list and returns it’s index. If the element occurs more than once it returns it’s smallest/first position. If element is not found, it raises a ValueError exception 
Syntax: list_var.index(item)
5)count(): The count() method returns the number of occurrences of an element in a list In simple terms, it counts how many times an element has occurred in a list and returns it.
Syntax: list_var.count(item)
6)remove(): The remove() method searches for the given element in the list and removes the first matching element. If the element(argument) passed to the remove() method doesn't exist, ValueError exception is thrown.
Syntax: list_var.remove(item)
7)pop(): The pop() method removes and returns the element at the given index (passed as an argument) from the list.
Syntax: list_var.pop(index)
8)clear(): The clear() method removes all items from the list.  It only empties the given list and doesn't return any value.
Syntax: list_var.clear( )
9)sort(): The sort() method sorts the elements of a given list. The order can be ascending or descending
Syntax: list_var.sort(reverse=True|False, key=name of func)
10)reverse(): The reverse() method reverses the elements of a given list. It doesn't return any value. It only reverses the elements and updates the list.
Syntax: list_var.reverse( )

List Comprehensions

Comprehensions are constructs that allow sequences to be built from other sequences. In simple words to build a List from another List or Set from another Set , we can use Comprehensions Python 2.0 introduced list comprehensions and Python 3.0 comes with dictionary and set comprehensions.
Syntax: list_variable = [x for x in iterable ]


myList=list(map(lambda x:x ,"Bhopal"))
print(myList)
Output

['B','H','O','P','A','L']
Explanation:
1) For a Python List Comprehension, we use the delimiters for a list- square brackets.
2) Inside those, we use a for-statement on an iterable.
3) Then there is an optional test condition we can apply on each member of iterable
4) Finally we have our output expression
Adding Conditions In List Comprehension
As previously mentioned , it is possible to add a test condition in List Comprehension. When we do this , we get only those items from the iterable for which the condition is True.
Syntax: list_variable = [x for x in iterable ]
Adding Conditions In List Comprehension
List Comprehension allows us to mention more than one if condition. To do this we simply have to mention the next if after the condition of first if
Syntax: list_variable = [x for x in iterable 'test_cond 1' 'test cond 2']
List Comprehension allows us to use logical or/and operator also but we should use only 1 if statement

a = [1,2,3,4,5,6,7,8,9,10]
b = [x for x in a if x % 2 == 0 or x % 3 == 0]
print(b)
Output

[2,3,4,6,8,9,10]
if-else in List comprehension
List Comprehension allows us to put if- else statements also But since in a comprehension, the first thing we specify is the value to put in a list, so we put our if-else in place of value.
Syntax: list_variable = [expr1 if cond else expr2 for x in iterable ]