Python Lists - Complete Notes
Introduction to Lists
What is a List?
A container used to store a list of values of any type
Mutable type - can change values in place without creating a fresh list
A type of sequence like tuples and strings, but differs in that lists are mutable while strings and tuples are immutable
Creating Lists
Lists are created using SQUARE BRACKETS [ ]
Examples of Lists:
[] - empty list
[1,2,3] - list of integers
[10,20,13.75,100.5,90] - list of integers and floats
["red","green","blue"] - list of strings
["E001","Rakesh",1,90000.5] - list of mixed values
['A', 'B', 'C'] - list of characters
Syntax:
ListName = [] # empty list
ListName = [value1, value2, ...] # list with values
Examples:
Family = ["father","mother","bro","sis"]
Student = [1,"Aman","XI",3150]
Creating Empty Lists
L = []
# OR
L = list()
Creating Long Lists
L = [1,2,3,44,55,66,77,88,99,4,3,5,6,7,88,100,300,12,13,14,56,78]
Nested Lists
L = [1,2,4,[100,200,300], 20]
This creates a list L with 5 elements (nested list counts as one element)
L[3] is itself a list of 3 elements
To access nested elements: L[3][1] returns 200
Creating Lists from Sequences
From Strings
L1 = list('welcome')
# Result: ['w','e','l','c','o','m','e']
From Tuples
T = ('A','B','C','D')
L1 = list(T)
# Result: ['A','B','C','D']
Creating Lists from User Input
Simple Input (creates string list)
list1 = list(input('Enter list elements'))
Values entered will be of STRING type
Using eval() for Proper Data Types
list1 = eval(input("enter list to be entered"))
print("list is", list1)
How eval() works:
eval('5+10') # Returns: 15
Y = eval("2*5") # Y = 10
Num = eval(input("enter any value"))
# If input is 20, output: 20 <class 'int'>
eval() converts to appropriate type:
Integers → int
Floats → float
Lists → list
Tuples → tuple
Example:
>>> list1 = eval(input("Enter values:"))
>>> Enter values: [10,20,30]
>>> list1
[10,20,30]
Accessing List Elements
Indexing
Lists use positive (0 to length-1) and negative (-1 to -length) indexing
Example:
Fruits = ["mango","apple","guava","pomegranate","cherry"]
Index Position Positive Index Negative Index Value
0 0 -5 mango
1 1 -4 apple
2 2 -3 guava
3 3 -2 pomegranate
4 4 -1 cherry
Accessing Individual Elements
>>> a = [1,2,3,4,5]
>>> a[1] # 2
>>> a[3] # 4
>>> a[-2] # 4
>>> a[5] # Error
Similarities with Strings
Common Operations:
1. Length - len() function
2. Indexing and Slicing
3. Membership operators - in and not in
4. Concatenation - + operator
5. Replication - * operator
Key Difference: Mutability
Strings are IMMUTABLE, Lists are MUTABLE
>>> student = [1,'Akash','XIA',3150]
>>> student[3] = 6300
>>> student
[1,'Akash','XIA',6300] # Successfully modified
Traversing Lists
Using for loop
val = [10,20,30,50,100]
for i in val:
print(i)
Printing with Index
val = [10,20,30,50,100]
length = len(val)
for i in range(length):
print("At Index", i, "and index", i-length, 'is:', val[i])
List Comparisons
Python allows relational operators: ==, >=, <=, !=, >, <
>>> L1 = [1,3,5]
>>> L2 = [1,3,5]
>>> L3 = [1,5,3]
>>> L1 == L2 # True
>>> L1 == L3 # False
>>> L1 < L3 # True
Comparison Logic:
Comparison Result Reason
[1,2,8,9] < [9,1] True 1<9
[1,2,8,9] < [1,2,9,1] True 8<9
[1,2,8,9] < [1,2,9,10] True 8<9
[1,2,8,9] < [1,2,8,4] False 9 < 4 is false
List Operations
Joining Lists (Concatenation)
Fruits = ["apple","mango","grapes"]
Veg = ["spinach","carrot","potato"]
Fveg = Fruits + Veg
# Result: ["apple","mango","grapes","spinach","carrot","potato"]
Note: Can only add list with another list, not with int, float, or string
Repeating/Replicating Lists
Fruits = ["apple","mango","grapes"]
Fruits * 2
# Result: ["apple","mango","grapes","apple","mango","grapes"]
List Slicing
Syntax: ListName[start:end] - from start index to end-1 index
val = [10,20,30,40,1,2,3,100,200]
print(val[0:3]) # [10, 20, 30]
print(val[3:8]) # [40, 1, 2, 3, 100]
print(val[-4:-1]) # [3, 100, 200]
print(val[::-1]) # Reverse list
Step Slicing
val = [10,20,30,40,1,2,3,100,200]
print(val[0:9:2]) # [10, 30, 1, 3, 200]
print(val[::3]) # Every 3rd element
print(val[::-2]) # Reverse with step 2
Slice Assignment
items = ["One","Two","Three","Four"]
items[0:2] = [1,2]
# Result: [1, 2, 'Three', 'Four']
items[0:3] = "Fantastic"
# Result: ['F','a','n','t','a','s','t','i','c','Four']
String Assignment:
>>> items = [1,2,3,4]
>>> items[3:] = "hello"
>>> items
[1,2,3,'h','e','l','l','o'] # Works because string is sequence
Error with non-sequence:
items[3:] = 100 # Error - int is not iterable
Modifying Lists
Appending Elements
>>> Items = [10,20,30]
>>> [Link](40)
>>> Items
[10,20,30,40]
Note: append() modifies list but does NOT return a value
Updating Elements
Items = [10,20,30,40]
Items[3] = 100
# Result: [10,20,30,100]
Deleting Elements
Single element:
Items = [10,20,30,40,50,60,70]
del Items[2]
# Result: [10,20,40,50,60,70]
Multiple elements:
Items = [10,20,30,40,50,60,70]
del Items[0:3]
# Result: [40,50,60,70]
Entire list:
del Items # List no longer exists
Using pop()
>>> Items = [10,20,30,40,50,60,70]
>>> [Link]() # Returns 70, deletes last item
>>> [Link](2) # Returns 30, deletes element at index 2
Can store deleted value:
N1 = [Link]()
N2 = [Link](3)
Copying Lists
Wrong Way (Creates Alias)
a = [10,20,30]
b = a # b is just an alias, not a copy
a[2] = 100
# Both a and b: [10,20,100]
Correct Way (True Copy)
>>> a = [10,20,30]
>>> b = list(a) # Creates independent copy
>>> a[2] = 100
>>> a # [10,20,100]
>>> b # [10,20,30]
List Functions and Methods
index()
Returns the index of first matched item
>>> L1 = [10,20,30,40,50,20]
>>> [Link](20)
1 # First occurrence at index 1
>>> [Link](100) # ValueError: not in list
append()
Adds single item to the end
>>> family = ["father","mother","bro","sis"]
>>> [Link]("Tommy")
>>> family
["father","mother","bro","sis","Tommy"]
Note: Does NOT return any value
extend()
Adds multiple items (list to list)
>>> subject1 = ["physics","chemistry","cs"]
>>> subject2 = ["english","maths"]
>>> [Link](subject2)
>>> subject1
['physics','chemistry','cs','english','maths']
Cannot add single values:
>>> [Link](300) # TypeError: 'int' object is not iterable
>>> [Link]([300,400]) # Works!
append() vs extend()
append():
>>> m1 = [1,2,3,4]
>>> [Link](5) # Works
>>> [Link](6,7) # Error: takes exactly one argument
>>> [Link]([6,7]) # Adds as nested list
>>> len(m1) # 6 (list within list)
extend():
>>> m2 = [100,200]
>>> [Link]([300,400])
>>> m2
[100,200,300,400]
>>> len(m2) # 4
insert()
Adds element at specific position
>>> L1 = [10,20,30,40,50]
>>> [Link](3, 35) # insert(position, item)
>>> L1
[10,20,30,35,40,50]
Special positions:
[Link](0, 5) # Beginning
[Link](len(L1),100) # End
[Link](-10, 2) # Beginning (negative beyond range)
pop()
Removes and returns element
>>> L1 = [10,20,30,40,50]
>>> [Link]() # Returns 50
>>> val = [Link](2) # Returns 30
>>> L1
[10,20,40]
Error on empty list:
>>> L1 = []
>>> [Link]() # IndexError: pop from empty list
remove()
Removes first occurrence by value
>>> L1 = [1,3,7,9,11,3,7]
>>> [Link](3)
>>> L1
[1,7,9,11,3,7] # Only first 3 removed
>>> [Link](10) # ValueError: not in list
clear()
Removes all elements, list still exists
>>> L1 = [10,20,30,40,50]
>>> [Link]()
>>> L1
[] # Empty list, but object exists
Note: Unlike del listname , clear() keeps the list object
count()
Returns count of specified item
>>> L1 = [10,20,30,40,20,30,100]
>>> [Link](20) # 2
>>> [Link](40) # 1
>>> [Link](11) # 0 (not in list)
reverse()
Reverses list in-place
>>> L1 = [10,20,30,40,20,30,100]
>>> [Link]()
>>> L1
[100,30,20,40,30,20,10]
Note: Does NOT return a value
sort()
Sorts list in-place
>>> L1 = [10,1,7,20,8,9,2]
>>> [Link]()
>>> L1
[1,2,7,8,9,10,20]
>>> L2 = ['g','e','a','c','b','d']
>>> [Link]()
>>> L2
['a','b','c','d','e','g']
Descending order:
>>> [Link](reverse=True)
>>> L1
[20,10,9,8,7,2,1]
Summary of Key Concepts
1. Lists are mutable - can be modified in place
2. Created with square brackets - []
3. Support positive and negative indexing
4. Support slicing operations
5. Can contain any data type including mixed types
6. Can be nested - lists within lists
7. Many built-in methods for manipulation
8. Methods like append(), extend(), sort(), reverse() modify in-place and don't return values
9. Methods like pop(), index() return values
10. Use list() to create true copies, not aliases
Source Material Credits: VINOD KUMAR VERMA, PGT(CS), KV OEF KANPUR & SACHIN BHARDWAJ, PGT(CS), KV
NO.1 TEZPUR
Website: [Link]