0% found this document useful (0 votes)
10 views10 pages

Python Lists: Creation and Operations

good notes

Uploaded by

kvnotes10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views10 pages

Python Lists: Creation and Operations

good notes

Uploaded by

kvnotes10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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: ==, >=, <=, !=, >, <

&gt;&gt;&gt; L1 = [1,3,5]
&gt;&gt;&gt; L2 = [1,3,5]
&gt;&gt;&gt; L3 = [1,5,3]
&gt;&gt;&gt; L1 == L2 # True
&gt;&gt;&gt; L1 == L3 # False
&gt;&gt;&gt; L1 &lt; 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:

&gt;&gt;&gt; items = [1,2,3,4]


&gt;&gt;&gt; items[3:] = "hello"
&gt;&gt;&gt; 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

&gt;&gt;&gt; Items = [10,20,30]


&gt;&gt;&gt; [Link](40)
&gt;&gt;&gt; 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()

&gt;&gt;&gt; Items = [10,20,30,40,50,60,70]


&gt;&gt;&gt; [Link]() # Returns 70, deletes last item
&gt;&gt;&gt; [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)

&gt;&gt;&gt; a = [10,20,30]
&gt;&gt;&gt; b = list(a) # Creates independent copy
&gt;&gt;&gt; a[2] = 100
&gt;&gt;&gt; a # [10,20,100]
&gt;&gt;&gt; b # [10,20,30]
List Functions and Methods

index()

Returns the index of first matched item

&gt;&gt;&gt; L1 = [10,20,30,40,50,20]
&gt;&gt;&gt; [Link](20)
1 # First occurrence at index 1
&gt;&gt;&gt; [Link](100) # ValueError: not in list

append()

Adds single item to the end

&gt;&gt;&gt; family = ["father","mother","bro","sis"]


&gt;&gt;&gt; [Link]("Tommy")
&gt;&gt;&gt; family
["father","mother","bro","sis","Tommy"]

Note: Does NOT return any value

extend()

Adds multiple items (list to list)

&gt;&gt;&gt; subject1 = ["physics","chemistry","cs"]


&gt;&gt;&gt; subject2 = ["english","maths"]
&gt;&gt;&gt; [Link](subject2)
&gt;&gt;&gt; subject1
['physics','chemistry','cs','english','maths']

Cannot add single values:

&gt;&gt;&gt; [Link](300) # TypeError: 'int' object is not iterable


&gt;&gt;&gt; [Link]([300,400]) # Works!

append() vs extend()
append():

&gt;&gt;&gt; m1 = [1,2,3,4]
&gt;&gt;&gt; [Link](5) # Works
&gt;&gt;&gt; [Link](6,7) # Error: takes exactly one argument
&gt;&gt;&gt; [Link]([6,7]) # Adds as nested list
&gt;&gt;&gt; len(m1) # 6 (list within list)

extend():

&gt;&gt;&gt; m2 = [100,200]
&gt;&gt;&gt; [Link]([300,400])
&gt;&gt;&gt; m2
[100,200,300,400]
&gt;&gt;&gt; len(m2) # 4
insert()
Adds element at specific position

&gt;&gt;&gt; L1 = [10,20,30,40,50]
&gt;&gt;&gt; [Link](3, 35) # insert(position, item)
&gt;&gt;&gt; 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

&gt;&gt;&gt; L1 = [10,20,30,40,50]
&gt;&gt;&gt; [Link]() # Returns 50
&gt;&gt;&gt; val = [Link](2) # Returns 30
&gt;&gt;&gt; L1
[10,20,40]

Error on empty list:

&gt;&gt;&gt; L1 = []
&gt;&gt;&gt; [Link]() # IndexError: pop from empty list

remove()
Removes first occurrence by value

&gt;&gt;&gt; L1 = [1,3,7,9,11,3,7]
&gt;&gt;&gt; [Link](3)
&gt;&gt;&gt; L1
[1,7,9,11,3,7] # Only first 3 removed
&gt;&gt;&gt; [Link](10) # ValueError: not in list

clear()
Removes all elements, list still exists

&gt;&gt;&gt; L1 = [10,20,30,40,50]
&gt;&gt;&gt; [Link]()
&gt;&gt;&gt; L1
[] # Empty list, but object exists

Note: Unlike del listname , clear() keeps the list object


count()
Returns count of specified item

&gt;&gt;&gt; L1 = [10,20,30,40,20,30,100]
&gt;&gt;&gt; [Link](20) # 2
&gt;&gt;&gt; [Link](40) # 1
&gt;&gt;&gt; [Link](11) # 0 (not in list)

reverse()
Reverses list in-place

&gt;&gt;&gt; L1 = [10,20,30,40,20,30,100]
&gt;&gt;&gt; [Link]()
&gt;&gt;&gt; L1
[100,30,20,40,30,20,10]

Note: Does NOT return a value

sort()
Sorts list in-place

&gt;&gt;&gt; L1 = [10,1,7,20,8,9,2]
&gt;&gt;&gt; [Link]()
&gt;&gt;&gt; L1
[1,2,7,8,9,10,20]

&gt;&gt;&gt; L2 = ['g','e','a','c','b','d']
&gt;&gt;&gt; [Link]()
&gt;&gt;&gt; L2
['a','b','c','d','e','g']

Descending order:

&gt;&gt;&gt; [Link](reverse=True)
&gt;&gt;&gt; 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]

You might also like