Python List
Python list is a data structure which is used to store various types of data.In Python, lists are mutable i.e., Python will not create a new list if we modify an element of the list.
It works as a container that holds other objects in a given order. We can perform various operations like insertion and deletion on list.A list can be composed by storing a sequence of different type of values separated by commas.
Python list is enclosed between square([]) brackets and elements are stored in the index basis with starting index 0.
Syantax :
<list_name>=[value1,value2,value3,...,valuen];
list=['foo','bar','baz','quz','quux','corge']
print(list)
my_list=[1,2,3,4,4.5,'apkzube','X']
print(my_list)
A list can be created by putting the value inside the square bracket and separated by comma.
Output of above program :
['foo', 'bar', 'baz', 'quz', 'quux', 'corge']
[1, 2, 3, 4, 4.5, 'apkzube', 'X']
- Syntax to Access Python List
<list_name>[index]
we can use slice operator to access list element.
<list_name>[start : stop : step]
Example :
list=['foo','bar','baz','quz','quux','corge']
print(list[2])
print(list[4:6])
print(list[-4:-1])
print(list[1:5:2])
print(list[-1: :-1]) #reverse list
output of above example :
baz
['quux', 'corge']
['baz', 'quz', 'quux']
['bar', 'quz']
['corge', 'quux', 'quz', 'baz', 'bar', 'foo']
Note: Internal Memory Organization:
List do not store the elements directly at the index. In fact a reference is stored at each index which subsequently refers to the object stored somewhere in the memory. This is due to the fact that some objects may be large enough than other objects and hence they are stored at some other memory location.
- Iteration of list : In Python, we can Iteration list using for loop is one of common way to Iteration list
list1=['a','b','c',1,2,3]
for x in list1 :
print(x)
output :
a
b
c
1
2
3
Python List Operations
Apart from creating and accessing elements from the list, Python allows us to perform various other operations on the list. Some common operations are given below
- Adding Python Lists
In Python, lists can be added by using the concatenation operator(+) to join two lists.
list1=['a','b','c']
list2=['x','y','z']
list3=list1+list2
print(list3)
output of above example :
['a', 'b', 'c', 'x', 'y', 'z']
Note: '+'operator implies that both the operands passed must be list else error will be shown.
let's run example :
list1=['a','b','c']
a='x'
print(list1+a)
output of above example :
Traceback (most recent call last):
File "main.py", line 11, in
print(list1+a)
TypeError: can only concatenate list (not "str") to list
- Python Replicating lists
Replicating means repeating, It can be performed by using '*' operator by a specific number of time.
Example :
list1=['a','b','c']
print(list1*3)
output of above example :
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
- Python List Slicing
A subpart of a list can be retrieved on the basis of index. This subpart is known as list slice. This feature allows us to get sub-list of specified start and end index.
<list_name>[start : stop : step]
Example :
list=['foo','bar','baz','quz','quux','corge']
print(list[4:6])
print(list[-4:-1])
print(list[1:5:2])
print(list[-1: :-1]) #reverse list
output of above example :
['quux', 'corge']
['baz', 'quz', 'quux']
['bar', 'quz']
['corge', 'quux', 'quz', 'baz', 'bar', 'foo']
Note: If the index provided in the list slice is outside the list, then it raises an IndexError exception.
Python List Other Operations
Apart from above operations various other functions can also be performed on List such as Updating, Appending and Deleting elements from a List.
- Updating List - To update or change the value of particular index of a list, assign the value to that particular index of the List.
Example :
data1=[5,10,15,20,25]
print("Values of list are: " )
print(data1)
data1[2]="Multiple of 5"
print("Values of list are: ")
print(data1)
output of above example :
Values of list are:
[5, 10, 15, 20, 25]
Values of list are:
[5, 10, 'Multiple of 5', 20, 25]
- Appending List - Python provides, append() method which is used to append i.e., add an element at the end of the existing elements.
Example :
list1=['a','b','c']
list1.append(1.5)
list1.append('x')
list1.append(['y','z']) #append list into list as single object
print(list1)
output of above example :
['a', 'b', 'c', 1.5, 'x', ['y', 'z']]
- Deleting Elements - In Python, del statement can be used to delete an element from the list. It can also be used to delete all items from startIndex to endIndex.
Example :
list1=['a','b','c']
print("data in list : ",list1)
del(list1[2])
print("new data in list : ",list1)
output of above example :
data in list : ['a', 'b', 'c']
new data in list : ['a', 'b']
Python Lists Function & Method
Python provides various Built-in functions and methods for Lists that we can apply on the list.
Following are the common list functions.
fun | Description |
---|---|
min(list) | It returns the minimum value from the list given. |
max(list) | It returns the largest value from the given list. |
len(list) | It returns number of elements in a list. |
cmp(list1,list2) | It compares the two list. No longer available in Python 3. |
list(seq) | It takes sequence types and converts them to lists |
- min(list) - this method is used to get min value from the list. In Python3 lists element's type should be same otherwise compiler throw ypeError.
Example :
list1 = ['a','b','c']
list2 = [1,2,3]
list3=['a','b','c',1,2,3]
print(min(list1)) #a
print(min(list2)) #1
print(min(list3)) #typeError
output of above example :
a
1
File "main.py", line 15, in
print(min(list3))
TypeError: unorderable types: int() < str()
- max() - The max() method returns the elements from the list with maximum value.
Example :
list1 = ['a','b','c']
list2 = [1,2,3]
list3=['a','b','c',1,2,3]
print(max(list1)) #c
print(max(list2)) #3
print(max(list3)) #typeEror
output of above example :
c
3
Traceback (most recent call last):
File "main.py", line 15, in
print(max(list3))
TypeError: unorderable types: int() > str()
- len() - The len() method returns the number of elements in the list.
Example :
list1 = ['a','b','c']
list2 = []
list3=['a','b','c',1,2,3]
print(len(list1))
print(len(list2))
print(len(list3))
output of above example :
3
0
6
- list() - The list() method takes sequence types and converts them to lists. This is used to convert a given tuple into list.
Tuple are very similar to lists with only difference that element values of a tuple can not be changed and tuple elements are put between parentheses instead of square bracket. This function also converts characters in a string into a list.
Example :
t= (1997, 'C++', 'Java', 'Python')
list1 = list(t)
print ("List elements : ", list1)
str = "ApkZube"
list2 = list(str)
print ("List elements : ", list2)
output of above example :
List elements : [1997, 'C++', 'Java', 'Python']
List elements : ['A', 'p', 'k', 'Z', 'u', 'b', 'e']
Python includes the following list methods
method | description |
---|---|
list.count(obj) | Returns count of how many times obj occurs in list |
list.extend(seq) | Appends the contents of seq to list |
list.append(obj) | Appends object obj to list |
list.index(obj) | Returns the lowest index in list that obj appears |
list.insert(index, obj) | Inserts object obj into list at offset index |
list.pop(obj = list[-1]) | Removes and returns last object or obj from list |
list.remove(obj) | Removes object obj from list |
list.reverse() | Reverses objects of list in place |
list.sort([func]) | Sorts objects of list, use compare func if given |
- count() - The count() method returns count of how many times obj occurs in list.
Example :
list1 =[1,2,3,'a','b','c',1,2,3]
print(list1.count(1))
print(list1.count('b'))
print(list1.count(4))
output of above example :
2
1
0
- append() - The append() method appends a passed obj into the existing list.
Example :
list1 =[1,2,3]
list1.append(4)
list1.append('apkzube')
list1.append(['a','b','c']) #append as single object
print(list1)
output of above example :
[1, 2, 3, 4, 'apkzube', ['a', 'b', 'c']]
- extend() - The extend() method appends the contents of seq to list.
list.extend([seq])
Example :
list1 =[1,2,3]
list1.extend([4])
list1.extend('apkzube')
list1.extend(['a','b','c'])
print(list1)
output of above example :
[1, 2, 3, 4, 'a', 'p', 'k', 'z', 'u', 'b', 'e', 'a', 'b', 'c']
- index() - The index() method returns the lowest index in list that obj appears.
Example :
list1 =['apkzube','python','java','c++',1,2,3]
print("index of java : ",list1.index('java'))
print("index of 2 : ",list1.index(2))
output of above example :
index of java : 2
index of 2 : 5
- insert() - The insert() method inserts object obj into list at offset index.
list.insert(index, obj)
index − This is the Index where the object obj need to be inserted.
obj − This is the Object to be inserted into the given list.
Example :
list1 =['apkzube','python','java','c++',1,2,3]
list1.insert(3,'C#')
print(list1)
output of above example :
['apkzube', 'python', 'java', 'C#', 'c++', 1, 2, 3]
- pop() - The pop() method removes and returns last object or obj from the list.
list.pop(index)
index− This is an optional parameter, index of the object to be removed from the list. by default its -1 [last element]
Example :
list1 =['apkzube','python','java','c++',1,2,3]
list1.pop() # 3 is pop
print(list1)
list1.pop(2) # list[2] = "java" pop
print(list1)
output of above example :
['apkzube', 'python', 'java', 'c++', 1, 2]
['apkzube', 'python', 'c++', 1, 2]
- remove(obj) - object to be removed from the list.
Example :
list1 =['apkzube','python','java','c++',1,2,3]
list1.remove("java")
print(list1)
list1.remove(2)
print(list1)
output of above example :
['apkzube', 'python', 'c++', 1, 2, 3]
['apkzube', 'python', 'c++', 1, 3]
- reverse() - The reverse() method reverses objects of list in place.
Example :
list1 =['apkzube','python','java','c++',1,2,3]
list1.reverse()
print(list1)
output of above example :
[3, 2, 1, 'c++', 'java', 'python', 'apkzube']
- sort() - The sort() method sorts objects of list, use compare function if given. but type of element in list should be same otherwise compiler throw typeError.
Example 1 :
list1 =[22,30,100,300,399]
list2=['z','ab','abc','a','b']
list1.sort()
list2.sort()
print(list1)
print(list2)
output of above example :
[22, 30, 100, 300, 399]
['a', 'ab', 'abc', 'b', 'z']
Example 2:
list3=['a','b',1,2]
list3.sort()
print(list3)
output of above example :
Traceback (most recent call last):
File "main.py", line 9, in
list3.sort()
TypeError: unorderable types: int() < str()