Python Useful Tuple Vs List Differences

Here're the quick differences between Tuple and List. This list is useful for your projects and interviews.
Tuple Vs. Lists in Python
List
- Comma-separated elements inside a square bracket [] make a list.
- The elements are indexed. It starts from '0'
- These you need to enclose in a single quote and separate by a comma.
- A list can contain another list, which is called a NESTED list.
- Use type() function to get the type of data it is.
- The list is mutable (you can change the data). The objects (elements) can be of different data types.
- Here're examples on the List.
Tuple
- The elements comma-separated and enclosed in parenthesis ()
- The elements are indexed. It starts from '0'
- A tuple can have heterogeneous data (integer, float, string, list, etc.)
- A tuple is immutable. So, you can't change the elements.
- Use the type() function to get the type of data it is.
- Here're examples of Tuple.
List Example
#Illustration of creating a list
new_list=[1, 2, 3, 4]
print(new_list)
# Homogeneous data elements
new_list1=[1, "John", 55.5]
print(new_list1)
# Heterogeneous data elements
new_list2=[111, [1, "Clara", 75.5]]
# Nested list
print(new_list2)
[1, 2, 3, 4]
[1, ‘John’, 55.5]
[111, [1, ‘Clara’, 75.5]]
Output
[1, 2, 3, 4]
[1, ‘John’, 55.5]
[111, [1, ‘Clara’, 75.5]]
Tuple Example
#Illustration of unpacking a tuple
new_tuple2=(111, [1, "Clara", 75.5], (2, "Simon", 80.5))
# Nested
tuple
print(new_tuple2)
x, y, z=new_tuple2
print(x)
print(y)
print(z)
Output
111
[1, ‘Clara’, 75.5]
(2, ‘Simon’, 80.5)
Comments
Post a Comment
Thanks for your message. We will get back you.