Python Lists and Tuples
Python Lists and Tuples
Registration no : COSC232101044
Class : BSCS 4A
Course : AI LAB
Lists
Definition
Lists are mutable, ordered collections of items. They can contain elements of different
types.
Characteristics
Mutable: You can change, add, or remove items after the list has been created.
Ordered: The items have a defined order, and that order will not change unless you
explicitly do so.
Syntax
# Creating a list
Common Operations
Accessing Elements: Use indexing to access list elements.
print(my_list[0]) # Output: 1
my_list[1] = 'orange'
my_list.append('grape')
my_list.remove('banana')
Operations
list1 = [1, 2, 3]
list2 = [4, 5]
list1 = [1, 2, 3]
repeated_list = list1 * 3
if 'apple' in my_list:
length = len(my_list)
print(length) # Output: 5
sublist = my_list[1:3]
Example
fruits = ['apple', 'banana', 'cherry']
fruits.append('date')
Tuples
Definition
Tuples are immutable, ordered collections of items. They can also contain elements of
different types.
Characteristics
Syntax
# Creating a tuple
Common Operations
print(my_tuple[0]) # Output: 1
Immutability: You cannot modify elements, but you can concatenate tuples.
Operations
tuple2 = (4, 5)
tuple1 = (1, 2, 3)
repeated_tuple = tuple1 * 3
if 'apple' in my_tuple:
length = len(my_tuple)
print(length) # Output: 5
subtuple = my_tuple[1:3]
Example
colors = ('red', 'green', 'blue')
Key Differences
Feature List Tuple
Conclusion
Lists and tuples are fundamental data structures in Python. Choose lists when you need a mutable
collection of items, and tuples when you need an immutable collection. Understanding these differences
will help you make efficient decisions in your Python programming.