Data Structures:
Data Structures are a way of organizing data so that it can be accessed more efficiently depending upon the situation. Data Structures are fundamentals of any programming language around which a program is built. Python helps to learn the fundamental of these data structures in a simpler way as compared to other programming languages.
Lists Python Lists are just like the arrays, declared in other languages which is an ordered collection of data. It is very flexible as the items in a list do not need to be of the same type
Tuple Python Tuple is a collection of Python objects much like a list but Tuples are immutable in nature i.e. the elements in the tuple cannot be added or removed once created. Just like a List, a Tuple can also contain elements of various types.
Dictionary Python dictionary is like hash tables in any other language with the time complexity of O(1). It is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value is provided in the dictionary to make it more optimized.
Difference between List, Tuple and set:
Mutability:
- List: Mutable, meaning you can modify its elements (add, remove, or change).
- Tuple: Immutable, once created, its elements cannot be changed.
- Set: Mutable, but each element must be unique, and the set itself is unordered.
Syntax:
- List: Defined using square brackets []
.
- Tuple: Defined using parentheses ()
.
- Set: Defined using curly braces {}
.
Order:
- List: Ordered, elements are indexed and maintain the order in which they were added.
- Tuple: Ordered, similar to lists, elements have a specific order.
- Set: Unordered, elements have no specific order.
Duplicates:
- List: Allows duplicate elements.
- Tuple: Allows duplicate elements.
- Set: Does not allow duplicate elements.
Use Cases:
- List: Suitable for sequences where the order and duplication of elements matter, and you need to modify the sequence.
- Tuple: Useful when the data should not be modified after creation and order is important.
- Set: Ideal for tasks that involve checking membership and ensuring uniqueness of elements.
# List
my_list = [1, 2, 3, 3, 4]
print(my_list) # Output: [1, 2, 3, 3, 4]
# Tuple
my_tuple = (1, 2, 3, 3, 4)
print(my_tuple) # Output: (1, 2, 3, 3, 4)
# Set
my_set = {1, 2, 3, 3, 4}
print(my_set) # Output: {1, 2, 3, 4}