So, what's the difference between tuple and list?
Answer: Both can contain mixed datatypes. Both can be arbitrarily nested. The only difference, is that a tuple cannot be changed.
# -*- coding: utf-8 -*- # python # list and tuple can contain mixed datatypes, and arbitrarily nested. my_list = [3, "4", [11, "12"], ("a", 2), 5] my_tuple = (3, "4", [11, "12"], ("a", 2), 5) print my_list print my_tuple
# -*- coding: utf-8 -*- # python # tuple cannot be changed my_list = [3, 4, 5] my_tuple = (3, 4, 5) my_list[0] = 9 my_tuple[0] = 9 # TypeError: 'tuple' object does not support item assignment print my_list print my_tuple
So, in practice, if you need a list but the elements or length never needs to change, then, use tuple, else, list.
There are a slew of tech geekers online who'll tell you that tuple is “heterogeneous” and list is “homogeneous”, or that tuple has identity, or that tuple has semantic meaning. They are the type that like to draw legs on a snake.
blog comments powered by Disqus