Recently, I have encountered many List operations. I feel that it is a very important basic data structure, and what I have mastered is not very solid. Here I find some List operations, common functions, and record them. I hope they will be useful to you. If there is any deviation in understanding, please correct it. Thank you!
(1) Merge of lists
Used: +, append(), extend(), insert()
# -*- coding: utf-8 -*- """ Created on Tue Aug 7 20:10:41 2018 @author: brave-man blog: http://www.cnblogs.com/zrmw/ """ a = [123, 'abc', 12.3, 'lao zhang'] b = ['lao li', 'lao wang', 'lao liu'] print(a + b) a.extend(b) print(a) a.insert(0, b) print(a) a.append(b) print(a)
Output:
[123, 'abc', 12.3, 'lao zhang', 'lao li', 'lao wang', 'lao liu'] [123, 'abc', 12.3, 'lao zhang', 'lao li', 'lao wang', 'lao liu'] [['lao li', 'lao wang', 'lao liu'], 123, 'abc', 12.3, 'lao zhang', 'lao li', 'lao wang', 'lao liu'] [['lao li', 'lao wang', 'lao liu'], 123, 'abc', 12.3, 'lao zhang', 'lao li', 'lao wang', 'lao liu', ['lao li', 'lao wang', 'lao liu']]
(2) Deletion and deep copy of list, assignment
Using the function: remove(), pop(), del
# -*- coding: utf-8 -*- """ Created on Tue Aug 7 20:10:41 2018 @author: brave-man blog: http://www.cnblogs.com/zrmw/ """ import copy a = [123, 'abc', 12.3, 'lao zhang'] b = ['lao li', 'lao wang', 'lao liu'] f = ['aabbcc', 223344] # Assignment, binding the same object, will change the original list c = a print(c.pop()) print('a', a) print('c', c) print(a is c) # Shallow copy, only copy the deepest objects, and operate on new variables # The original list will not be affected d = b.copy() d.remove('lao li') print('b', b) print('d', d) print(b is d) # Deep copy, which copies each layer of the original list in memory and becomes a new # List, the operation on the new list will not affect the original list e = copy.deepcopy(f) print('e', e) del e[0] print('f', f) print('e', e) print(e is f)
Output:
lao zhang a [123, 'abc', 12.3] c [123, 'abc', 12.3] True b ['lao li', 'lao wang', 'lao liu'] d ['lao wang', 'lao liu'] False e ['aabbcc', 223344] f ['aabbcc', 223344] e [223344] False