Why we have tuple and list in python
The most notable difference between tuple and list is that tuple is immutable and list is mutable. But why we have this two ?
- Performance and cost
Tuple is immutable so you can not change it. Once you create it, it is done. It will be a fixed memory area(may not be continues). But list is difference. Once you create a list you may need to add more element to it. So python will reserve some space for you when you create a list. Even you will not add element to it.
So the size of tuple will be less than the size of list
>>> t = ('a','b','c')
>>> l = ['a','b','c']
>>> import sys
>>> sys.getsizeof(l)
96
>>> sys.getsizeof(t)
80
- Usage scenario
Suppose you have a data structure record a location in a book. You can use (100,28) to represent the location. 100 is the page number and 28 is the line. Because the location in a book can not be changed once it got printed. So you should never change the location data structure. Then tuple will be more suitable for it.
If you want to save multi-locations, you can put use a list to contain these tuple.
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步