Lists in Python
• Definition:
Lists are ordered collections used to store multiple items in a single variable.
• Characteristics:
o Ordered — items maintain the order in which they are inserted.
o Mutable — items can be changed after creation (add, remove, update).
o Allow duplicate elements.
• Syntax:python
my_list = [1, 2, 3, "apple", True]
• Indexing and slicing:
o Supports indexing (e.g., my_list[0] gives first item).
o Supports slicing (e.g., my_list[1:3] gives items from index 1 to 2).
• Common methods:
o append() — add an item to the end.
o insert() — add an item at a specific position.
o remove() — remove a specific item.
o pop() — remove item at a specific index (default last).
o sort() — sort items (if all elements are comparable).
o reverse() — reverse the list order.
o clear() — remove all items.
• Example:
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
print(fruits) # ['apple', 'banana', 'cherry', 'orange']
• When to use:
o When you need a collection that can be modified.
o When order matters.
Tuples in Python
• Definition:
Tuples are ordered collections used to store multiple items, but they cannot be
changed after creation.
• Characteristics:
o Ordered — items maintain insertion order.
o Immutable — cannot change, add, or remove items after creation.
o Allow duplicate elements.
• Syntax:
my_tuple = (1, 2, 3, "apple", True)
• Indexing and slicing:
o Supports indexing (e.g., my_tuple[0]).
o Supports slicing (e.g., my_tuple[1:4]).
• Methods:
o Fewer methods than lists because they are immutable.
o count() — count occurrences of a value.
o index() — return the first index of a value.
• Example:
colors = ("red", "green", "blue")
print(colors[1]) # green
• Advantages:
o Faster than lists (because they are immutable).
o Can be used as keys in dictionaries (if they contain only immutable items).
• When to use:
o When you want to ensure data cannot be changed.
o When using fixed sets of values (e.g., days of the week).
Key Differences (quick glance)
Feature List Tuple
Ordered Yes Yes
Mutable Yes No
Duplicates Yes Yes
allowed
Methods Many Few
Speed Slower Faster