Strings, Lists, Sets, and Tuples
Python offers a variety of collection data types to store and manage groups of values. Each one has different properties depending on how you want to access, update, or organize your data.
Strings (str)
A string is a sequence of characters enclosed in quotes (' '
or " "
). Strings are immutable, meaning they cannot be changed after creation.
You can:
- Access characters by index
- Slice a portion:
message[0:5]
→"Hello"
- Use string methods like
lower()
,upper()
,replace()
, etc.
Lists (list)
A list is an ordered, mutable collection that allows duplicates. Use square brackets []
.
You can:
- Add items:
fruits.append("orange")
- Change values:
fruits[0] = "grape"
- Remove items:
fruits.remove("banana")
Lists are best when you need to modify, sort, or loop through a collection in order.
Tuples (tuples)
A tuple is like a list, but immutable—you can’t change its elements after creation. Use parentheses ()
.
Tuples are useful when you want to ensure the data remains constant, like coordinates, colors, or fixed values.
Sets (set)
A set is an unordered, mutable, and unique collection—duplicates are not allowed. Use curly braces {}
.
Sets are great for:
- Eliminating duplicates
- Performing set operations like union, intersection:
Note: Sets are unordered, so you can’t access elements by index.
Summary
Type | Ordered | Mutable | Allows Duplicates | Indexed |
---|---|---|---|---|
String | ✅ | ❌ | ✅ | ✅ |
List | ✅ | ✅ | ✅ | ✅ |
Tuple | ✅ | ❌ | ✅ | ✅ |
Set | ❌ | ✅ | ❌ | ❌ |