SoFunction
Updated on 2024-11-20

Several ways to add elements to a list in python (+, append, extend)

1. Use the + plus sign

The + plus sign is adding two list lists to return a new list object, which consumes extra memory.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
if __name__ == '__main__':
    a = [1, 2, 3]
    b = [4, 5, 6]
    c = a + b
    print(c)

Output:

[1, 2, 3, 4, 5, 6]
Process finished with exit code 0

2. Using the append() method

The append() method adds a new object to the end of the list, which has no return value but modifies the original list.

Syntax: (obj)

Parameters: obj - object to add to the end of the list.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
if __name__ == '__main__':
    a = [1, 2, 3]
    b = [4, 5, 6]
    (b)
    print(a)

Output:

[1, 2, 3, [4, 5, 6]]
Process finished with exit code 0

3. Use the extend() method

The extend() method extends the original list with a new list, adding the object iteration to the back of the list, and only supports data from iterable objects. (Iterable objects: objects that can be iterated over with a for loop are iterable objects, such as strings, lists, tuples, dictionaries, collections, etc.)

This method has no return value, but adds new list contents to an already existing list.

Syntax: (seq)

Parameters: seq - list of elements.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
if __name__ == '__main__':
    a = [1, 2, 3]
    b = [4, 5, 6]
    (b)
    print(a)

Output:

[1, 2, 3, 4, 5, 6]
Process finished with exit code 0

4. Difficulties

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
if __name__ == '__main__':
    a = [1, 2, 3]
    c = []
    (a)
    print(c)
    (4)
    print(c)

Output:

[[1, 2, 3]]
[[1, 2, 3, 4]]
Process finished with exit code 0

You can see that after changing the a list, the c list has also changed.

The reason for this phenomenon is that when the list list is appended using the append() method, it is actually caused by a shallow copy.

Solution: You can use () for deep copy.

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import copy
 
if __name__ == '__main__':
    a = [1, 2, 3]
    c = []
    ((a))
    print(c)
    (4)
    print(c)

Output:

[[1, 2, 3]]
[[1, 2, 3]]

Process finished with exit code 0

to this article on python list add elements of several ways (+, append (), extend ()) of the article is introduced to this, more related to python list add elements of content, please search for my previous posts or continue to browse the following related articles I hope that you will support me more in the future!