Posted at: https://laptrinhcanban.com/en
When working on projects with python, you will probably have problems with having to insert an element into a list python . Let’s learn how to insert elements into a list python by insert method or python list slicing function in this lesson.
We use the method insert(), or use slicing list to insert elements into List python.
Insert element at the specified position in the python list using the insert methodvị trí xác định trong list python bằng phương thức insert
Syntax of inserting elements into the specified position in the python list with the method insert() as follows:
List
.insert
(index
, value
)
Inside:
- List is the original list
- index is the position to add an element to the original list
- giá trị is the value of the element to be added.
Here, index
and value
is called parameter of the method insert().
The element to be added will be added to the position in front of the index specified in the list.
How to define the index in the python list, please review the index in python post .
Specifically, we need to write the following:
mylist = ["A", "B", "C"] |
As you can see, the character Z
has been added to the position before index 1 (the letter B), that is, between the letter A
and B
then right?
Let’s look at a more complex example:
mylist = [ "Blue" , "Red" , "Green" ] |
Like above, you can easily insert elements at the specified position in the python list using the insert method .
Insert elements into python list with slice function
In the previous lesson, we learned how to change an element or slice a list from the original list using the slice function in Python . In fact, you can completely use this function to insert elements into List python.
The idea here is to use slices to specify an empty range (no elements exist) and insert a new list into that blank.
The syntax we need to use is as follows:
ordinary list
[index
: index
] = add list
Here, we write list[ index: index]
to specify an empty range at the position indexin the original list. Then we will insert this blank with the list to add.
And add list
(located to the right of the sign =
) will be added in front of ordinary list
.
Specifically, we need to write the following:
mylist = [ "A" , "B" , "C" ] |
We can manipulate numeric analogy in python like in the following example:
mylist = [ "1" , "2" , "3" ] |
Summarize
Above, Kiyoshi showed you how to insert element into python list by insert method or python list slicing function . To better understand the lesson content, you should practice with the following examples.
And let’s learn more about Python in the next lessons.
mylist = [ "Blue" , "Red" , "Green" ] |
URL Link
HOME › python for beginners>>list in python