SoFunction
Updated on 2024-11-10

python add list element append,extend and insert

I. Using the + sign to add list elements

In general the two lists are merged together is also a way to add elements, as long as the use of the + sign direct arithmetic can be, the following is the demo code.

name1 = ['python', 'java', 'php', 'MySql']
 
name2 = ['C++', 'C', 'C#']
 
total = name1 + name2
 
print(name1)
 
print(name2)
 
print(total)
 
The results of the run are as follows:
 
['python', 'java', 'php', 'MySql']
['C++', 'C', 'C#']
['python', 'java', 'php', 'MySql', 'C++', 'C', 'C#']

Second, use the append () method to add list elements

append()method is available in many languages, this method is an append element, which appends a single element or a single object or another list to the end of the list. All elements, lists, or objects added are individual elements of the list, and are added as a whole, not one by one like the + sign.

1. Add a single element

name1 = ['python', 'java', 'php']
 
('MySql')
 
print(name1)

Returns results:

['python', 'java', 'php', 'MySql']

2. Add objects

name1 = ['python', 'java', 'php']# ('MySql')
 
name2 = ('MySql', 'SQL')
 
(name2)
 
print(name1)

Returns results:

['python', 'java', 'php', ('MySql', 'SQL')]

3. Add another list

name1 = ['python', 'java', 'php']
 
# ('MySql')
 
# name2 = ('MySql', 'SQL')
 
name2 = ['C++', 'C', 'C#']
 
(name2)
 
print(name1)

Third, extend () method to add elements

The difference between extend() and append() is:extend() doesn't treat the list or metazoans as a whole, but adds the elements they contain to the list one by one.

name1 = ['python', 'java', 'php']
 
name2 = ('MySql', 'SQL')
 
(name2)
 
name3 = ['C++', 'C', 'C#']
 
(name3)
 
print(name1)

Returns results:

['python', 'java', 'php', 'MySql', 'SQL', 'C++', 'C', 'C#']

Fourth, insert () method to add elements

The previous methods add elements to the end of the list.insert()method adds an element to the list at the specified position.

It's going to be demonstrated below:

name1 = ['python', 'java', 'php']
 
(2, 'MySql')
 
print(name1)

Returns results:

['python', 'java', 'MySql', 'php']

The above code we insert an element at index position 2, run the results can be seen and we think the index position seems to be different, this is because of our understanding of the error, here 2 is to insert the element to be placed at index position 2.insert()method can also insert other objects or lists

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