Python List Tuple and Set
In Python, lists, tuples, and sets are all data structures that can be used to store collections of data.
List
- Definition: A list is an ordered collection of items that are mutable (i.e., you can change their contents).
- Syntax: Lists are defined using square brackets
[]
.
- Characteristics:
- Allows duplicate elements.
- Elements can be of different data types.
- Supports indexing and slicing.
- Commonly used methods:
append()
, extend()
, insert()
, remove()
, pop()
, clear()
, index()
, count()
, sort()
, reverse()
.
Tuple
-
Definition: A tuple is an ordered collection of items that are immutable (i.e., you cannot change their contents after creation).
-
Syntax: Tuples are defined using parentheses ()
.
-
Characteristics:
- Allows duplicate elements.
- Elements can be of different data types.
- Supports indexing and slicing.
- Fewer built-in methods compared to lists (e.g.,
count()
, index()
).
Set
- Definition: A set is an unordered collection of unique items.
- Syntax: Sets are defined using curly braces
{}
or the set()
function.
- Characteristics:
- Does not allow duplicate elements.
- Elements can be of different data types.
- Does not support indexing or slicing (because it is unordered).
- Commonly used methods:
add()
, update()
, remove()
, discard()
, pop()
, clear()
, union()
, intersection()
, difference()
, symmetric_difference()
.
Enroll Now
- Python Programming
- Machine Learning