zoukankan      html  css  js  c++  java
  • 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 ?

    1. 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
    
    1. 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.

  • 相关阅读:
    day_5.25py
    day_5.24py
    day_5.22 py
    numpy模块 03
    requests 模块例题示范
    logging模块
    typing 模块
    hashlib模块和hmac模块
    random模块
    time和datetime模块
  • 原文地址:https://www.cnblogs.com/kramer/p/6024118.html
Copyright © 2011-2022 走看看