Python Programming - Lists, Tuples, Dictionaries (UNIT – Iv)
UNIT – Iv
Python
Programming - Lists, Tuples, Dictionaries
1. Creating a List
Definition:
- A list is an ordered,
mutable (changeable) collection of elements in Python.
- Lists can store different
data types — integers, strings, floats, or even other lists.
Syntax:
list_name = [element1, element2, element3, ...]
Example:
numbers = [10, 20, 30, 40]
names = ["Murugan", "Shanmugam",
"Karthikeyan"]
mixed = [1, "apple", 3.5, True]
Using the
list() constructor:
data = list((1, 2, 3, 4))
Important
Points:
- Lists are indexed
starting from 0.
- Lists are mutable,
meaning elements can be changed after creation.
2. Accessing Values in a List
Indexing:
- Each element in a list has a
position number (index).
- Positive indexing starts from 0.
- Negative indexing starts from -1 (last
element).
Example:
fruits = ["apple", "banana",
"cherry", "grapes"]
print(fruits[0])
# Output: apple
print(fruits[-1])
# Output: grapes
Slicing:
- Used to access a range
of elements.
print(fruits[1:3])
# Output: ['banana', 'cherry']
print(fruits[:2])
# Output: ['apple', 'banana']
print(fruits[::2])
# Output: ['apple', 'cherry']
Using
loops:
for fruit in fruits:
print(fruit)
3. Updating Values in Lists
Reassigning
by Index:
numbers = [10, 20, 30, 40]
numbers[2] = 99
print(numbers)
# Output: [10, 20, 99, 40]
Updating
using Slicing:
numbers[1:3] = [11, 22]
print(numbers)
# Output: [10, 11, 22, 40]
Adding
Elements:
- append() → adds one element at end
- extend() → adds multiple elements
- insert() → adds element at specific
index
Example:
nums = [1, 2, 3]
nums.append(4)
nums.extend([5, 6])
nums.insert(1, 10)
print(nums)
# Output: [1, 10, 2, 3, 4, 5, 6]
4. Nested Lists
Definition:
- A list inside another
list is called a nested list.
- Used to represent matrices,
tables, or multidimensional data.
Example:
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9] ]
Accessing
Nested Elements:
print(matrix[0]) # Output: [1, 2, 3]
print(matrix[1][2]) # Output: 6
Updating
Nested Lists:
matrix[2][1] = 88
print(matrix)
Output:
[[1, 2, 3], [4, 5, 6], [7, 88, 9]]
5. Basic List Operations
|
Operation |
Example |
Output |
Description |
|
+ |
[1,2] + [3,4] |
[1,2,3,4] |
Concatenation |
|
* |
[5] * 3 |
[5,5,5] |
Repetition |
|
in |
2 in [1,2,3] |
True |
Membership |
|
len() |
len([10,20,30]) |
3 |
Length |
|
min() |
min([4,2,8]) |
2 |
Minimum
value |
|
max() |
max([4,2,8]) |
8 |
Maximum
value |
Example:
list1 = [1, 2, 3]
list2 = [4, 5]
print(list1 + list2) # [1,2,3,4,5]
print(list1 * 2) # [1,2,3,1,2,3]
print(3 in list1) # True
print(len(list1))
# 3
6. List Methods (Important Built-in
Functions)
|
Method |
Description |
Example |
|
append(x) |
Adds
element x at end |
a.append(5) |
|
extend(list) |
Adds
multiple elements |
a.extend([4,5]) |
|
insert(i,x) |
Inserts
x at index i |
a.insert(2,99) |
|
remove(x) |
Removes
first occurrence of x |
a.remove(3) |
|
pop(i) |
Removes
element at index i |
a.pop(1) |
|
index(x) |
Returns
position of x |
a.index(10) |
|
count(x) |
Counts
how many times x appears |
a.count(4) |
|
sort() |
Sorts
list ascending |
a.sort() |
|
reverse() |
Reverses
list order |
a.reverse() |
|
clear() |
Removes
all elements |
a.clear() |
Example:
marks = [90, 85, 95, 70]
marks.sort()
marks.append(100)
marks.remove(85)
print(marks)
Output: [70, 90, 95, 100]
II. Tuples
in Python
1.
Definition
- A tuple is an ordered,
immutable collection of elements.
- It can store elements of different
data types (integers, strings, floats, etc.).
- Tuples are written inside parentheses
( ) and elements are separated
by commas.
Example:
my_tuple = (10, 20, 30, "Hello")
2.
Creating Tuples
You can
create tuples in several ways:
(a) Empty
Tuple
t1 = ()
(b) Tuple
with Elements
t2 = (10, 20, 30)
(c)
Without Parentheses (Tuple Packing)
t3 = 10, 20, 30
(d) Using
tuple() Constructor
t4 = tuple([1, 2, 3, 4])
(e)
Single Element Tuple
- A single element tuple must
have a comma after the element.
t5 = (10,)
# Correct
t6 = (10)
# This is just an integer
3.
Accessing Elements in a Tuple
- Tuples are indexed,
so we can access elements using indexes.
- Index starts from 0.
Example:
t = (5, 10, 15, 20)
print(t[0])
# Output: 5
print(t[-1])
# Output: 20 (negative indexing)
Tuple
Slicing:
print(t[1:3])
# Output: (10, 15)
4.
Updating Elements
- Tuples are immutable, so their elements cannot
be changed or updated after creation.
Example:
t = (1, 2, 3)
t[0] = 100
# ❌ Error: 'tuple' object does not support item assignment
But we
can create a new tuple from existing ones:
t1 = (1, 2, 3)
t2 = (4, 5)
t3 = t1 + t2
# Concatenation
print(t3)
# (1, 2, 3, 4, 5)
5.
Deleting Elements
- You cannot delete
specific elements in a tuple.
- But you can delete the
entire tuple using del.
Example:
t = (10, 20, 30)
del t
If you
now try to print t, it will cause an error because
the tuple no longer exists.
6. Nested
Tuples
- A nested tuple means
a tuple inside another tuple.
- You can access inner
elements using multiple indexes.
Example:
nested = (1, 2, (3, 4, 5), (6, 7))
print(nested[2]) # Output: (3, 4, 5)
print(nested[2][1]) # Output: 4
7. Tuple
Operations
|
Operation |
Description |
Example |
Output |
|
Concatenation |
Combines
two tuples |
(1,2)+(3,4) |
(1,2,3,4) |
|
Repetition |
Repeats
tuple elements |
(1,2)*3 |
(1,2,1,2,1,2) |
|
Membership |
Checks
if element exists |
2 in
(1,2,3) |
True |
|
Length |
Returns
number of elements |
len((1,2,3)) |
3 |
8.
Difference Between Lists and Tuples
|
Feature |
List |
Tuple |
|
Syntax |
Written
in [ ] |
Written
in ( ) |
|
Mutability |
Mutable
(can change elements) |
Immutable
(cannot change elements) |
|
Performance |
Slower
(due to mutability) |
Faster
(due to immutability) |
|
Methods
Available |
Many
(append, remove, etc.) |
Few
(count, index) |
|
Use
Case |
When
data can change |
When
data should remain constant |
|
Example |
L = [1,2,3] |
T = (1,2,3) |
9. Common
Tuple Functions
|
Function |
Description |
Example |
Output |
|
len(t) |
Returns
length |
len((1,2,3)) |
3 |
|
max(t) |
Largest
element |
max((1,5,2)) |
5 |
|
min(t) |
Smallest
element |
min((1,5,2)) |
1 |
|
sum(t) |
Sum of
elements |
sum((1,2,3)) |
6 |
|
tuple(iterable) |
Converts
to tuple |
tuple([1,2,3]) |
(1,2,3) |
10.
Summary (Key Points for Exam)
- Tuples are immutable,
ordered collections.
- Created using ( ) or tuple().
- Elements accessed via indexing
and slicing.
- Cannot modify or delete elements directly.
- Nested tuples allow tuples within tuples.
- Faster and memory efficient
compared to lists.
- Used for fixed data,
such as coordinates, constants, etc.
III. Dictionaries
in Python
1.
Definition
- A dictionary is an unordered
collection of key–value pairs.
- Each key is unique
and is used to access its corresponding value.
- Dictionaries are written
inside curly braces { }.
- Syntax:
·
dictionary_name
= {key1: value1, key2: value2, ...}
Example:
student = {"name": "Arun",
"age": 20, "course": "CSE"}
2.
Creating Dictionaries
(a) Empty
Dictionary
d1 = {}
(b)
Dictionary with Data
d2 = {"id": 101, "name":
"Deepa", "marks": 95}
(c) Using
dict() Constructor
d3 = dict(name="Ravi", age=21,
dept="ECE")
3.
Accessing Elements in a Dictionary
Elements
are accessed using keys, not indexes.
Example:
student = {"name": "Kumar",
"age": 22, "course": "IT"}
print(student["name"]) # Output: Kumar
print(student.get("age")) # Output: 22
Note: If a key is not found,
·
student["height"] → Error
·
student.get("height") → Returns None
4.
Updating Elements
You can change
the value of an existing key or add a new key–value pair.
Example:
student = {"name": "Kumar",
"age": 22}
student["age"] = 23 # update existing key
student["course"] = "CSE" # add new key
print(student)
# Output: {'name': 'Kumar', 'age': 23, 'course':
'CSE'}
5.
Deleting Elements
|
Operation |
Example |
Description |
|
del dict[key] |
del student["age"] |
Deletes
key and its value |
|
dict.pop(key) |
student.pop("name") |
Removes
and returns value |
|
dict.popitem() |
student.popitem() |
Removes
the last inserted item |
|
dict.clear() |
student.clear() |
Removes
all elements |
|
del dict |
del student |
Deletes
the entire dictionary |
6.
Dictionary Functions and Methods
|
Function/Method |
Description |
Example |
Output |
|
len(d) |
Returns
number of items |
len(d) |
3 |
|
str(d) |
String
representation |
str(d) |
"{'a':
1, 'b': 2}" |
|
d.keys() |
Returns
all keys |
d.keys() |
dict_keys(['a',
'b']) |
|
d.values() |
Returns
all values |
d.values() |
dict_values([1,
2]) |
|
d.items() |
Returns
key–value pairs |
d.items() |
dict_items([('a',1),('b',2)]) |
|
d.update(d2) |
Adds
all items from d2 |
d.update({'c':3}) |
Adds
new pair |
|
d.copy() |
Returns
a shallow copy |
d2 = d.copy() |
— |
|
d.get(key, default) |
Returns
value if key exists |
d.get('x', 0) |
0 if
not found |
|
d.fromkeys(seq, value) |
Creates
new dict with given keys and value |
dict.fromkeys(['a','b'], 0) |
{'a':0,
'b':0} |
7.
Iterating Through Dictionary
You can
loop through keys, values, or both:
Example:
student = {"name": "Murugan",
"age": 23, "dept": "CSE"}
for key in student:
print(key, ":", student[key])
8. Nested
Dictionaries
A
dictionary can contain another dictionary as a value.
Example:
students = {
"s1": {"name": "Krishnan",
"age": 21},
"s2": {"name": "Bala", "age":
22}
}
print(students["s1"]["name"]) # Output: Krishnan
9.
Difference Between Lists and Dictionaries
|
Feature |
List |
Dictionary |
|
Syntax |
[ ] |
{ } |
|
Structure |
Ordered
collection of elements |
Unordered
collection of key–value pairs |
|
Access |
By
index |
By key |
|
Mutability |
Mutable |
Mutable |
|
Duplicate
elements |
Allowed |
Keys
must be unique |
|
Example |
[10, 20, 30] |
{'a':10, 'b':20} |
|
Use
case |
When
only values matter |
When
values need names (keys) |
Summary
- Dictionary stores key–value
pairs inside {}.
- Keys are unique and immutable
(numbers, strings, tuples).
- Access using key names,
not index positions.
- You can add, modify, or
delete entries easily.
- Common methods: keys(), values(), items(), update(), pop().
- Efficient for data retrieval using
keys.
Comments
Post a Comment