Can we convert list to a tuple?

Can we convert list to a tuple?

Yes, an existing list can be converted to tuple type cast. Below is an example,

numbers_list = [1,2,3,4,5,6,34,54,21,78]
numbers_tuple = tuple(numbers_list)
numbers_tuple[0] = 5

numbers_list is a list and has several elements. We converted to tuple numbers_tuple using tuple type cast. So, numbers_tuple is a tuple now and is immutable so we cannot change any element in the tuple. When we try to assign '5' to first element in tuple using numbers_tuple[0] = 5 we get following error.

TypeError: 'tuple' object does not support item assignment

Post a Comment

0 Comments