0% found this document useful (0 votes)
9 views3 pages

CSC 23F 078 (CS3B) Ass#01 (Ai)

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)
9 views3 pages

CSC 23F 078 (CS3B) Ass#01 (Ai)

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
You are on page 1/ 3

Department of Computer Science

Name: Malik Muhammad Umer


Student ID: CSC-23F-078
Course: Artificial Intelligence
Course Instructor: Ma’am Sadaf
In Python, lists and tuples are both used to store collections of items, but they
have some key differences:

Key Differences between List and Tuple

List:
• Mutable, meaning you can modify (add, remove, or change) elements.
• Defined with square brackets [].
• Slower compared to tuples in some operations due to mutability.
• Used when the collection of items needs to be changed.

Code:
# Defining a List
my_list = [1, 2, 3, 4]

print("Original List:", my_list)

# Modifying the List (mutable)

my_list[2] = 10

my_list.append(5)

print("Modified List:", my_list)

Output:
Original List: [1, 2, 3, 4]

Modified List: [1, 2, 10, 4, 5]


Tuple:
• Immutable, meaning you cannot modify its elements after it is created.
• Defined with parentheses ().
• Slightly faster because of immutability.
• Used for fixed data that should not be changed, like coordinates or
constant values.

Code:
# Defining a Tuple

my_tuple = (1, 2, 3, 4)

print("\nOriginal Tuple:", my_tuple)

# Trying to Modify the Tuple (immutable)


try:

my_tuple[2] = 10 # This will raise an error


except TypeError as e:

print("Error:", e)
# Tuples are immutable, so you cannot add or change items.

Output:
Original Tuple: (1, 2, 3, 4)

Error: 'tuple' object does not support item assignment

You might also like