In Python, List, Tuple, Set, and Dictionary are four fundamental data structures used for organizing and storing data. The key difference is, that Lists and tuples are ordered collections in Python, but lists are mutable while tuples are immutable. Sets are unordered collections of unique elements, while dictionaries are key-value pairs for efficient data retrieval. Sets store unique elements, while dictionaries store related pieces of information.
What is List in Python?
A list is a collection of ordered elements. Lists can be of different data types such as integers, floats, strings etc. Various operations such as adding or removing elements or searching and sorting for elements can be performed in a list in Python.
Implementation
# Create a list of numbers
Python_list = [1, 2, 3, 4, 5]
# Change an item in the list by index
Python_list[2] = 6
# Add an item to the end of the list
Python_list.append(7)
# Remove an item from the list by value
Python_list.remove(4)
# Print the list
print(Python_list)
Output
Explanation
In the code, we initialized a list [1, 2, 3, 4, 5] and performed operations first. We changed the third element to 6 and then appended 7 to the end of the list, and finally removed element 4 from the list.
Applications of List
- Lists can be used to store and access sequential data.
- We can modify elements in a List because Lists are mutable.
What is Tuple in Python?
A tuple is a sequence of elements separated by commas and enclosed in parentheses. Tuples are similar to lists, but they cannot be modified once created. This means that you cannot add, remove or modify elements of a tuple.
Implementation
# Create a list of numbers
Python_tuple = (1, 2, 3, 4, 5)
# Print first three elements of tuple
print(Python_tuple[:3])
Output
Explanation
In the above code, we have implemented a tuple (1, 2, 3, 4, 5), and we print the first three elements in the tuple i.e., (1, 2, 3).
Let’s try deleting from the tuple.
# Deleting a tuple
tuple_del = (1, 2, 3, 4, 5)
# Delete tuple using del
del tuple_del
print(tuple_del)
Output
Explanation
In the above code we have implemented a tuple (1, 2, 3, 4, 5) and we delete the tuple using ‘del’. Therefore we get an error as the tuple does not exist.
Applications of Tuple
- Unlike Lists, Tuples are immutable and can be used to store dictionary keys.
- Tuples can return multiple values from a function, such as you can use a tuple to return minimum and maximum values from a list.