Python中的内存管理之python list内存使用详解

前言

使用 Python 的时候,我们知道 list 是一个长度可变对的数组, 可以通过 insert,append 和 extend 轻易的拓展其中的元素个数。 也可以使用运算符 如: [1] + [2] 生成新的数组[1, 2]

extend()、 "+"、"+=" 的区别

  • "+"将两个 list 相加,会返回到一个新的 list 对象
  • append 在原 list 上进行修改,没有返回值

从以下代码可以看到, 调用 b = b + [3, 4] 之后, 通过id(b) 查看 b 变成了一个新对象。

In [5]: b = [1, 2]
In [6]: id(b)
Out[6]: 1628740249224

In [7]: b = b + [3, 4]
In [8]: id(b)
Out[8]: 1628740456520

使用extend() 完成相同的步骤, 可以看到 对象c 的id保持和原来的一致

In [9]: c = [1, 2]
In [10]: id(c)
Out[10]: 1628740392584

In [11]: c.extend([3, 4])
In [12]: id(c)
Out[12]: 1628740392584

使用 "+="  连接列表, 看到效果和 extend() 是相同的。

In [1]: a = [1, 2]
In [2]: id(a)
Out[2]: 1628740021448

In [3]: a += [3, 4]
In [4]: id(a)
Out[4]: 1628740021448

结论: 减少内存的拷贝, 修改一个列表的数据时, 应避免使用 list1 = list1 + list2 这样的语法。

List的内存使用

一个示例:

In [1]: import sys

In [2]: lst1 = [1]
In [3]: lst2 = []
In [4]: lst2.append(1)

In [5]: lst1 == lst2
Out[5]: True

In [6]: sys.getsizeof(lst1)
Out[6]: 72
In [7]: sys.getsizeof(lst2)
Out[7]: 96

可以看到,lst1 == lst2, 但是当使用 sys.getsizeof 获取对象的内存大小时, 两者却是不同的。

如下图所示, list_a 长度为4, 当执行 append(4) 时, 底层的数据长度其实申请了4个元素的空间,当再次执行 append(5) 的时候,不需要再次申请内存。

因为 执行 append() 操作时,Python将一次拓展N个元素的内存,因为一个 append 操作很可能是很多 append 操作的开始,通过额外分配内存来减少可能的内存分配和内存copy的次数。

In [1]: import sys
 
In [2]: l = []
   ...: print(f'list initial size {sys.getsizeof(l)}')
   ...: for i in range(80):
   ...:     cur_size = sys.getsizeof(l)
   ...:     l.append(i)
   ...:     new_size = sys.getsizeof(l)
   ...:     print(f'list len {i+1}:\t current_size {new_size}\t new_allocated 8 * {(new_size-cur_size)/8}')
   ...:
list initial size 64
list len 1:      current_size 96         new_allocated 8 * 4.0
list len 2:      current_size 96         new_allocated 8 * 0.0
list len 3:      current_size 96         new_allocated 8 * 0.0
list len 4:      current_size 96         new_allocated 8 * 0.0
list len 5:      current_size 128        new_allocated 8 * 4.0
list len 6:      current_size 128        new_allocated 8 * 0.0
list len 7:      current_size 128        new_allocated 8 * 0.0
list len 8:      current_size 128        new_allocated 8 * 0.0
list len 9:      current_size 192        new_allocated 8 * 8.0
list len 10:     current_size 192        new_allocated 8 * 0.0
list len 11:     current_size 192        new_allocated 8 * 0.0
list len 12:     current_size 192        new_allocated 8 * 0.0
list len 13:     current_size 192        new_allocated 8 * 0.0
list len 14:     current_size 192        new_allocated 8 * 0.0
list len 15:     current_size 192        new_allocated 8 * 0.0
list len 16:     current_size 192        new_allocated 8 * 0.0
list len 17:     current_size 264        new_allocated 8 * 9.0
list len 18:     current_size 264        new_allocated 8 * 0.0
list len 19:     current_size 264        new_allocated 8 * 0.0
list len 20:     current_size 264        new_allocated 8 * 0.0
list len 21:     current_size 264        new_allocated 8 * 0.0
list len 22:     current_size 264        new_allocated 8 * 0.0
list len 23:     current_size 264        new_allocated 8 * 0.0
list len 24:     current_size 264        new_allocated 8 * 0.0
list len 25:     current_size 264        new_allocated 8 * 0.0
list len 26:     current_size 344        new_allocated 8 * 10.0
list len 27:     current_size 344        new_allocated 8 * 0.0
list len 28:     current_size 344        new_allocated 8 * 0.0
list len 29:     current_size 344        new_allocated 8 * 0.0
list len 30:     current_size 344        new_allocated 8 * 0.0
list len 31:     current_size 344        new_allocated 8 * 0.0
list len 32:     current_size 344        new_allocated 8 * 0.0
list len 33:     current_size 344        new_allocated 8 * 0.0
list len 34:     current_size 344        new_allocated 8 * 0.0
list len 35:     current_size 344        new_allocated 8 * 0.0
list len 36:     current_size 432        new_allocated 8 * 11.0
list len 37:     current_size 432        new_allocated 8 * 0.0
list len 38:     current_size 432        new_allocated 8 * 0.0
list len 39:     current_size 432        new_allocated 8 * 0.0
list len 40:     current_size 432        new_allocated 8 * 0.0
list len 41:     current_size 432        new_allocated 8 * 0.0
list len 42:     current_size 432        new_allocated 8 * 0.0
list len 43:     current_size 432        new_allocated 8 * 0.0
list len 44:     current_size 432        new_allocated 8 * 0.0
list len 45:     current_size 432        new_allocated 8 * 0.0
list len 46:     current_size 432        new_allocated 8 * 0.0
list len 47:     current_size 528        new_allocated 8 * 12.0
list len 48:     current_size 528        new_allocated 8 * 0.0
list len 49:     current_size 528        new_allocated 8 * 0.0
list len 50:     current_size 528        new_allocated 8 * 0.0
list len 51:     current_size 528        new_allocated 8 * 0.0
list len 52:     current_size 528        new_allocated 8 * 0.0
list len 53:     current_size 528        new_allocated 8 * 0.0
list len 54:     current_size 528        new_allocated 8 * 0.0
list len 55:     current_size 528        new_allocated 8 * 0.0
list len 56:     current_size 528        new_allocated 8 * 0.0
list len 57:     current_size 528        new_allocated 8 * 0.0
list len 58:     current_size 528        new_allocated 8 * 0.0
list len 59:     current_size 640        new_allocated 8 * 14.0
list len 60:     current_size 640        new_allocated 8 * 0.0
list len 61:     current_size 640        new_allocated 8 * 0.0
list len 62:     current_size 640        new_allocated 8 * 0.0
list len 63:     current_size 640        new_allocated 8 * 0.0
list len 64:     current_size 640        new_allocated 8 * 0.0
list len 65:     current_size 640        new_allocated 8 * 0.0
list len 66:     current_size 640        new_allocated 8 * 0.0
list len 67:     current_size 640        new_allocated 8 * 0.0
list len 68:     current_size 640        new_allocated 8 * 0.0
list len 69:     current_size 640        new_allocated 8 * 0.0
list len 70:     current_size 640        new_allocated 8 * 0.0
list len 71:     current_size 640        new_allocated 8 * 0.0
list len 72:     current_size 640        new_allocated 8 * 0.0
list len 73:     current_size 768        new_allocated 8 * 16.0
list len 74:     current_size 768        new_allocated 8 * 0.0
list len 75:     current_size 768        new_allocated 8 * 0.0
list len 76:     current_size 768        new_allocated 8 * 0.0
list len 77:     current_size 768        new_allocated 8 * 0.0
list len 78:     current_size 768        new_allocated 8 * 0.0
list len 79:     current_size 768        new_allocated 8 * 0.0
list len 80:     current_size 768        new_allocated 8 * 0.0

通过观察可以发现, 列表从0 增加到 80长度的过程中, 新申请的内存长度为 [4, 4, 8, 9, 10, 11, 12, 13, 14, 16] 。 反之, 当执行 remove 或者 pop 减少列表中的数据时, 列表也会自动缩容。

  • 扩容条件 ,新长度大于底层数组长度;
  • 缩容条件 ,新长度小于底层数组长度的一半;

结论: 避免使用类似 append 语法初始化列表, 优先使用列表表达式

# Bad ❌
list_a = []
for i in range(50):
    list_a.append(i)

# Good ✔️
list_b = [i for i in range(50)]

结论:

① 避免使用 "+" 修改数组

② 尽量避免多次使用 append 函数

到此这篇关于Python中的内存管理之python list内存使用详解的文章就介绍到这了,更多相关python list内存使用内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • python数据分析之DataFrame内存优化

    目录 1. pandas查看数据占用大小 2. 对数据进行压缩 3. 参考资料

  • 用python监控服务器的cpu,磁盘空间,内存,超过邮件报警

    监控Linux服务器嘛,脚本逻辑基本上是用os.popen模块,然后把获取到的结果通过split切分成一个list,再拿目标list值和我阈值对比,超过就邮件报警: 邮件是通过Linux的mailx发出去的,可自行搜索安装该模块,关键字:"Linux使用mailx发邮件",脚本如下: 一.cpu ideal值,不小于20% #!/usr/bin/python # -*- coding: utf-8 -*-   import datetime import os     f = os.p

  • Python numpy大矩阵运算内存不足如何解决

    程序运行,产生如下结果,然后进程终止,导致这一结果的原因很有可能是内存爆炸. 当两个较大的 (e.g., 10000*10000 维)ndarray 做运算(加法,or 乘法)时,很容易出现这样的结果. 解决办法: 大多数情况下,这种大矩阵都是稀疏的.尽可能地利用稀疏计算的方式,例如稀疏矩阵,或者只计算非 0 位置的值. 如果都是整数运算,可以设置 dtype=int,而非 dtype=float, 可以省下不少空间. linux 系统下,使用 top 命令,可以很容易地看到内存(%MEM) 的

  • Python内存泄漏和内存溢出的解决方案

    一.内存泄漏 像Java程序一样,虽然Python本身也有垃圾回收的功能,但是同样也会产生内存泄漏的问题. 对于一个用 python 实现的,长期运行的后台服务进程来说,如果内存持续增长,那么很可能是有了"内存泄露". 1.内存泄露的原因 对于 python 这种支持垃圾回收的语言来说,怎么还会有内存泄露? 概括来说,有以下三种原因: 所用到的用 C 语言开发的底层模块中出现了内存泄露. 代码中用到了全局的 list. dict 或其它容器,不停的往这些容器中插入对象,而忘记了在使用完

  • 总结python 三种常见的内存泄漏场景

    概要 不要以为 Python 有自动垃圾回收就不会内存泄漏,本着它有"垃圾回收"我有"垃圾代码"的精神,现在总结一下三种常见的内存泄漏场景. 无穷大导致内存泄漏 如果把内存泄漏定义成只申请不释放,那么借着 Python 中整数可以无穷大的这个特点,我们一行代码就可以完成内存泄漏了. i = 1024 ** 1024 ** 1024 循环引用导致内存泄漏 引用记数器 是 Python 垃圾回收机制的基础,如果一个对象的引用数量不为 0 那么是不会被垃圾回收的,我们可以

  • python切片中内存的注意事项总结

    1.由于 Python 列表的切片会在内存中创建新对象,因此需要注意的另一个重要函数是itertools.islice. 2.通常需要遍历切片,而不仅仅是在内存中静态创建它.islice非常适合这个. 一个警告,它不支持负的参数start,stop或者step,如果这是一个问题,您可能需要计算指标或反向迭代提前. length = 100 last_nine_iter = itertools.islice(list(range(length)), length-9, None, 1) list_

  • 基于Python中单例模式的几种实现方式及优化详解

    单例模式 单例模式(Singleton Pattern)是一种常用的软件设计模式,该模式的主要目的是确保某一个类只有一个实例存在.当你希望在整个系统中,某个类只能出现一个实例时,单例对象就能派上用场. 比如,某个服务器程序的配置信息存放在一个文件中,客户端通过一个 AppConfig 的类来读取配置文件的信息.如果在程序运行期间,有很多地方都需要使用配置文件的内容,也就是说,很多地方都需要创建 AppConfig 对象的实例,这就导致系统中存在多个 AppConfig 的实例对象,而这样会严重浪

  • Python中的CSV文件使用"with"语句的方式详解

    是否可以直接使用with语句与CSV文件?能够做这样的事情似乎很自然: import csv with csv.reader(open("myfile.csv")) as reader: # do things with reader 但是csv.reader不提供__enter__和__exit__方法,所以这不行.但是我可以分两步做: import csv with open("myfile.csv") as f: reader = csv.reader(f)

  • Python中关于元组 集合 字符串 函数 异常处理的全面详解

    目录 元组 集合 字符串 1.字符串的驻留机制 2.常用操作 函数 1.函数的优点: 2.函数的创建:def 函数名([输入参数]) 3.函数的参数传递: 4.函数的返回值: 5.函数的参数定义: 6.变量的作用区域 7.递归函数:函数体内套用该函数本身 8.将函数存储在模块中 9.函数编写指南: Bug 1.Bug常见类型 2.常见异常类型 3.python异常处理机制 pycharm开发环境的调试 编程思想 (1)两种编程思想 (2)类和对象的创建 元组 元组是不可变序列 多任务环境下,同时

  • 对python中的for循环和range内置函数详解

    如下所示: 1.for循环和range内置函数配合使用 range函数生成一个从零开始的列表, range(4)表示list:0123 range(1,11,2)表示从1开始到11-1为止步长为2的list:13579 即range(i)表示从0开始到i-1的列表,range(m,n)表示从m开始到n-1的列表,range(m,n,t)表示从m开始步长为t到n-1的列表 ''' print('第一次循环输出:') for i in range(4): print(i) print('第二次循环输

  • 对python中xlsx,csv以及json文件的相互转化方法详解

    最近需要各种转格式,这里对相关代码作一个记录,方便日后查询. xlsx文件转csv文件 import xlrd import csv def xlsx_to_csv(): workbook = xlrd.open_workbook('1.xlsx') table = workbook.sheet_by_index(0) with codecs.open('1.csv', 'w', encoding='utf-8') as f: write = csv.writer(f) for row_num

  • 对python中的float除法和整除法的实例详解

    从python2.2开始,便有两种除法运算符:"/"."//".两者最大区别在: python2.2前的版本和python2.2以后3.0以前的版本的默认情况下,"/"所做的除法是以一种两个数或者多个数出现一个浮点数结果就以浮点数的形式表示,即float除法 "//"所做的除法则不相同,"//"不管两者出现任何数,都以整除结果为准,不对小数部分进行处理,直接抛弃,也就是整除法 以下是笔者在编译器测试的数据,

  • 对Python中一维向量和一维向量转置相乘的方法详解

    在Python中有时会碰到需要一个一维列向量(n*1)与另一个一维列向量(n*1)的转置(1*n)相乘,得到一个n*n的矩阵的情况.但是在python中, 我们发现,无论是".T"还是"np.transpose"都无法实现一维向量的转置,相比之下,Matlab一句" a' "就能实现了. 那怎么实现呢?我找了个方法.请看: 即,我们把向量reshape一下,如此便实现了一维向量与一维向量转置相乘为矩阵的目的. 若大家有其他方法望告知. 以上这篇对

  • 对python中的*args与**kwgs的含义与作用详解

    在定义函数的时候参数通常会使用 *args与**kwgs,形参与实参的区别不再赘述,我们来解释一下这两个的作用. *args是非关键字参数,用于元组,**kw是关键字参数 例如下面的代码 def foo(*args,**kwargs): print 'args is',args print 'kwargs is',kwargs foo(1,2) foo(k=1,w=2,a=3,r=4,g=5,s=6) foo(1,2,a=1,b=2,c=2) foo('a',1,None,a=1,b='2',c

  • 对python中的乘法dot和对应分量相乘multiply详解

    向量点乘 (dot) 和对应分量相乘 (multiply) : >>> a array([1, 2, 3]) >>> b array([ 1., 1., 1.]) >>> np.multiply(a,b) array([ 1., 2., 3.]) >>> np.dot(a,b) 6.0 矩阵乘法 (dot) 和对应分量相乘 (multiply) : >>> c matrix([[1, 2, 3]]) >>

  • 浅谈python中统计计数的几种方法和Counter详解

    1) 使用字典dict() 循环遍历出一个可迭代对象中的元素,如果字典没有该元素,那么就让该元素作为字典的键,并将该键赋值为1,如果存在就将该元素对应的值加1. lists = ['a','a','b',5,6,7,5] count_dict = dict() for item in lists: if item in count_dict: count_dict[item] += 1 else: count_dict[item] = 1 2) 使用defaultdict() defaultdi

随机推荐