Python List
Python List
Python List
In this class, we'll learn everything about Python lists, how they are created, slicing of a list,
adding or removing elements from them and so on.
Python offers a range of compound data types often referred to as sequences. List is one of
the most frequently used and very versatile data types used in Python.
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.
Summary
Data types Type
String immutable
List mutable ✎
It can have any number of items and they may be of different types (integer, float, string
etc.).
Syantax:
<list_name>=[value1,value2,value3,...,valuen]
In [1]: # Example:
# list of integers
my_list1 = [1, 2, 3]
print(my_list1) # ▶ [1, 2, 3]
# nested list
my_list3 = ["mouse", [9, 3, 6], ['a']]
print(my_list3) # ▶ ["mouse", [9, 3, 6], ['a']]
my_list4=['foo','bar','baz','quz','quux','corge']
print(my_list4) # ▶ ['foo','bar','baz','quz','quux','corge']
my_list5=[1,2,3,4,4.5,'helloworld','X']
print(my_list5) # ▶ [1,2,3,4,4.5,'helloworld','X']
[]
0
[1, 2, 3]
[1, 'Hello', 3.4]
['mouse', [9, 3, 6], ['a']]
['foo', 'bar', 'baz', 'quz', 'quux', 'corge']
[1, 2, 3, 4, 4.5, 'helloworld', 'X']
List Index
We can use the index operator [] to access an item in a list. In Python, indices start at 0.
So, a list having 5 elements will have an index from 0 to 4.
Trying to access indexes other than these will raise an IndexError . The index must be an
integer. We can't use float or other types, this will result in TypeError .
print(my_list[0]) # ▶ p
print(my_list[2]) # ▶ o
print(my_list[4]) # ▶ e
# Nested List
n_list = ["Happy", [2, 0, 1, 5]]
# Nested indexing
print(n_list[0][1]) # ▶ a
print(n_list[1][3]) # ▶ 5
p
o
e
a
5
localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_List.… 2/15
2/15/25, 7:40 PM 003_Python_List
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-0a4959e7a13b> in <module>
14 print(n_list[1][3]) # ▶ 5
15
---> 16 print(my_list[4.0]) # ▶ TypeError: list indices must be integers or slice
s, not float
Negative indexing
Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2
to the second last item and so on.
my_list = ['p','r','o','b','e']
print(my_list[-1]) # ▶ e
print(my_list[-5]) # ▶ p
e
p
Note: If the index provided in the list slice is outside the list, then it raises an
IndexError exception.
Syntax:
my_list = ['p','r','o','g','r','a','m','i','n','g']
# indes [ 0 1 2 3 4 5 6 7 8 9 ]
# index [-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 ]
Slicing can be best visualized by considering the index to be between the elements as shown
below. So if we want to access a range, we need two indices that will slice that portion from
the list.
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.
In [5]: # Example:
list=['foo','bar','baz','quz','quux','corge']
print(list[2]) # ▶ baz
print(list[0:]) # ▶ ['foo', 'bar', 'baz', 'quz', 'quux', 'corge'] ∵ if we d
print(list[4:6]) # ▶ ['quux', 'corge']
print(list[-4:-1]) # ▶ ['baz', 'quz', 'quux'] ∵ it does not include the end in
print(list[1:5:2]) # ▶ ['bar', 'quz'] ∵ it does not include the end index
print(list[-1: :-1]) # ▶ ['corge', 'quux', 'quz', 'baz', 'bar', 'foo'] ∵ reverse
print(list[-1]) # ▶ corge ∵ last element
print(list[-2]) # ▶ quux ∵ second last element
print(len(list)-1) # ▶ 5 ∵ index of last element
baz
['foo', 'bar', 'baz', 'quz', 'quux', 'corge']
['quux', 'corge']
['baz', 'quz', 'quux']
['bar', 'quz']
['corge', 'quux', 'quz', 'baz', 'bar', 'foo']
corge
quux
5
True
[1, 4, 6, 8]
[1, 3, 5, 7]
In [7]: # Example:
data1=[5,10,15,20,25]
print(data1) # ▶ [5, 10, 15, 20, 25]
data1[2]="Multiple of 5" # we are modifying the 3rd element using its index [2]
print(data1) # ▶ [5, 10, 'Multiple of 5', 20, 25]
We can add one item to a list using the append() method or add several items using
extend() method.
odd = [1, 3, 5]
odd.append(7)
print(odd) # ▶ [1, 3, 5, 7]
[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]
In [9]: # 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) # ▶ ['a', 'b', 'c', 1.5, 'x', ['y', 'z']]
We can also use + (concatenation) operator to combine two lists. This is also called
concatenation.
odd = [1, 3, 5]
print(odd + [9, 7, 5]) # ▶ [1, 3, 5, 9, 7, 5]
[1, 3, 5, 9, 7, 5]
In [11]: # Example:
list1=['a','b','c']
list2=['x','y','z']
list3=list1+list2
print(list3) # ▶ ['a', 'b', 'c', 'x', 'y', 'z']
In [12]: # Example:
list1=['a','b','c']
a='x'
print(list1+a) # ▶ TypeError: can only concatenate list (not "str") to list
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-12-4ed3868a9a2e> in <module>
3 list1=['a','b','c']
4 a='x'
----> 5 print(list1+a) # ▶ TypeError: can only concatenate list (not "str") to li
st
NOTE: + operator implies that both the operands passed must be list else
error will be shown.
The '*' operator repeats a list for the given number of times.
odd = [1, 3, 5]
[1, 3, 5, 9, 7, 5]
['re', 're', 're']
In [14]: # Example:
list1=['a','b','c']
print(list1*3) # ▶ quux ∵
print(["re"] * 3) # ▶ quux ∵
Furthermore, we can insert one item at a desired location by using the method insert()
or insert multiple items by squeezing it into an empty slice of a list.
odd = [1, 9]
odd.insert(1,3)
print(odd) # ▶ [1, 3, 9]
odd[2:2] = [5, 7]
print(odd) # ▶ [1, 3, 5, 7, 9]
[1, 3, 9]
[1, 3, 5, 7, 9]
We can delete one or more items from a list using the keyword del . It can even delete the
list entirely.
In [17]: # Example:
list1=['a','b','c']
print("data in list : ",list1) # ▶ data in list : ['a', 'b', 'c']
del(list1[2])
print("new data in list : ",list1) # ▶ new data in list : ['a', 'b']
We can use remove() method to remove the given item or pop() method to remove an
item at the given index.
The pop() method removes and returns the last item if the index is not provided. This
helps us implement lists as stacks (first in, last out data structure).
In [18]: # Example:
my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')
my_list.clear()
print(my_list) # ▶ []
Finally, we can also delete items in a list by assigning an empty list to a slice of elements.
In [19]: # Example:
my_list = ['p','r','o','b','l','e','m']
my_list[2:3] = []
print(my_list) # ▶ ['p', 'r', 'b', 'l', 'e', 'm']
my_list[2:-2] = []
print(my_list) # ▶ ['p', 'r', 'e', 'm']
Functions Description
any() Returns True if any key of the list is true. If the list is empty, return False .
l = [1, 3, 4, 5]
print(all(l)) # ▶ True ∵ all values true
l = [0, False]
print(all(l)) # ▶ False ∵ all values false
l = [1, 3, 4, 0]
print(all(l)) # ▶ False ∵ one false value
l = [0, False, 5]
print(all(l)) # ▶ False ∵ one true value
l = []
print(all(l)) # ▶ True ∵ empty iterable
True
False
False
False
True
l = [1, 3, 4, 0]
print(any(l)) # ▶ True
l = [0, False]
print(any(l)) # ▶ False ∵ both are False
l = [0, False, 5]
print(any(l)) # ▶ True ∵ 5 is true
l = []
print(any(l)) # ▶ False ∵ iterable is empty
True
False
True
False
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: '<' not supported between instances of 'int' and
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)) # ▶ TypeError: '>' not supported between instances of 'int' and
c
3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-24-8f0bbdfdf6e5> in <module>
7 print(max(list1)) # ▶ c
8 print(max(list2)) # ▶ 3
----> 9 print(max(list3)) # ▶ TypeError: '>' not supported between instances of
'int' and 'str'
list1 = ['a','b','c']
list2 = []
list3=['a','b','c',1,2,3]
print(len(list1)) # ▶ 3
print(len(list2)) # ▶ 0
print(len(list3)) # ▶ 6
3
0
6
Method Description
list1 =[1,2,3]
list1.append(4)
list1.append('helloworld')
list1.append(['a','b','c']) #append as single object
print(list1) # ▶ [1, 2, 3, 4, 'helloworld', ['a', 'b', 'c']]
list1 =[1,2,3]
list1.extend([4])
list1.extend('helloworld')
list1.extend(['a','b','c'])
print(list1) # ▶ [1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', '
[1, 2, 3, 4, 'h', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd', 'a', 'b', 'c']
list1 =['helloworld','python','java','c++',1,2,3]
list1.insert(3,'C#')
print(list1) # ▶ ['helloworld', 'python', 'java', 'C#', 'c++', 1, 2, 3]
list1 =['helloworld','python','java','c++',1,2,3]
list1.remove("java")
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 2, 3]
list1.remove(2)
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 3]
list1 =['helloworld','python','java','c++',1,2,3]
list1.pop() # pop last element
print(list1) # ▶ ['helloworld', 'python', 'java', 'c++', 1, 2]
list1.pop(2) # pop element with index 2
print(list1) # ▶ ['helloworld', 'python', 'c++', 1, 2]
list1: []
list1 =['helloworld','python','java','c++',1,2,3]
print("index of java : ",list1.index('java')) # ▶ index of java : 2
print("index of 2 : ",list1.index(2)) # ▶ index of 2 : 5
index of java : 2
index of 2 : 5
list1 =[1,2,3,'a','b','c',1,2,3]
localhost:8888/nbconvert/html/Desktop/subjects/python programming/02_Python_Datatypes-main/02_Python_Datatypes-main/003_Python_Lis… 12/15
2/15/25, 7:40 PM 003_Python_List
print(list1.count(1)) # ▶ 2
print(list1.count('b')) # ▶ 1
print(list1.count(4)) # ▶ 0
2
1
0
list1 =[22,30,100,300,399]
list2=['z','ab','abc','a','b']
list1.sort()
list2.sort()
print(list1) # ▶ [22, 30, 100, 300, 399]
list1.sort(reverse=True)
print(list1) # ▶ [399, 300, 100, 30, 22]
print(list2) # ▶ ['a', 'ab', 'abc', 'b', 'z']
In [35]: # Example:
list3=['a','b',1,2]
list3.sort()
print(list3) # ▶ TypeError: '<' not supported between instances of 'int' and 'str
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-35-b942612e6b6a> in <module>
2
3 list3=['a','b',1,2]
----> 4 list3.sort()
5 print(list3) # ▶ TypeError: '<' not supported between instances of 'int'
and 'str'
list1 =['helloworld','python','java','c++',1,2,3]
list1.reverse()
print(list1) # ▶ [3, 2, 1, 'c++', 'java', 'python', 'helloworld']
Here is a complete list of all the built-in methods to work with List in Python.
A list comprehension consists of an expression followed by for loop inside square brackets.
Here is an example to make a list with each item being increasing power of 2.
In [39]: pow2 = []
for x in range(10):
pow2.append(2 ** x)
print(pow2) # ▶ [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]
# Output: True
print('p' in my_list) # ▶ True
# Output: False
print('a' in my_list) # ▶ False
# Output: True
print('c' not in my_list) # ▶ True
True
False
True
I like apple
I like banana
I like mango
In [45]: # Example:
list1=['a','b','c',1,2,3]
for x in list1 :
print(x)
a
b
c
1
2
3
I like apple
I like banana
I like mango
In [ ]: