Hướng dẫn add element to index python - thêm phần tử vào chỉ mục python

Phương thức Python Danh sách Chèn () chèn một phần tử đã cho tại một chỉ mục đã cho trong danh sách bằng Python. & NBSP;insert() method inserts a given element at a given index in a list using Python. 

Python Danh sách chèn () cú pháp

Cú pháp: list_name.insert (chỉ mục, phần tử)list_name.insert(index, element)

Parameters:  

  • Chỉ mục: Chỉ mục mà phần tử phải được chèn. the index at which the element has to be inserted.
  • Phần tử: Phần tử được chèn vào danh sách. the element to be inserted in the list.

Trả về: Không trả về bất kỳ giá trị nào.Does not return any value.

Ví dụ về danh sách python ()

Phương thức Python chèn () với chuỗi trong Python. with string in Python.

Python3

[1, 2, 3, 4, 10, 5, 6, 7]
6
[1, 2, 3, 4, 10, 5, 6, 7]
7
[1, 2, 3, 4, 10, 5, 6, 7]
8
[1, 2, 3, 4, 10, 5, 6, 7]
9
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
[1, 2, 3, 4, 10, 5, 6, 7]
9
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
2

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
3
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
4
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
6
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
7

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
8
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
9

Output:

['Geeks', 'For', 'Geeks']

Ví dụ 1: Chèn một phần tử vào danh sách Inserting an Element into the List

Ở đây, chúng tôi đang chèn 10 ở vị trí thứ 5 (chỉ số thứ 4) trong danh sách Python.

Python3

[1, 2, 13, 3, 4, 5, 6]
0
[1, 2, 3, 4, 10, 5, 6, 7]
7
[1, 2, 13, 3, 4, 5, 6]
2
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
4
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
[1, 2, 13, 3, 4, 5, 6]
5
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
[1, 2, 13, 3, 4, 5, 6]
7
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
[1, 2, 13, 3, 4, 5, 6]
9
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
[1, 2, (4, 5, 6), 3, 4, 5, 6]
1__

[1, 2, (4, 5, 6), 3, 4, 5, 6]
7
[1, 2, 13, 3, 4, 5, 6]
9
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
0
>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
1

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
8
>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
3

Output:  

[1, 2, 3, 4, 10, 5, 6, 7]

Ví dụ 2: Phương thức Lỗi của Chèn () Error of insert() Method

Ở đây, chúng tôi đang chèn 1 ở vị trí thứ 10 trong danh sách Python, chúng tôi sẽ gặp lỗi, nếu chúng tôi cố gắng chèn bất cứ thứ gì vào một chuỗi vì chuỗi không có thuộc tính chèn ().

Python3

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
4
[1, 2, 3, 4, 10, 5, 6, 7]
7
>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
6

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
7
>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
0
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
0
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
4
Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
7

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
8
>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
3

Output:  

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'

Ví dụ 3: Chèn vào danh sách trước bất kỳ phần tử nàoInsertion in a List Before any Element

Ở đây, chúng tôi đang chèn 13 ở vị trí thứ 3 trước 3 trong danh sách Python.

Python3

Các

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
9
[1, 2, 3, 4, 10, 5, 6, 7]
7 ________ 81 & nbsp;

python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
2
[1, 2, 3, 4, 10, 5, 6, 7]
7 ________ 37 & nbsp;

python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
5
[1, 2, 3, 4, 10, 5, 6, 7]
7
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
7

python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
8

Traceback (most recent call last):
  File "/home/2fe54bd8723cd0ae89a17325da8b2eb5.py",
   line 7, in 
    string.insert(10, 1)
AttributeError: 'str' object has no attribute 'insert'
8
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
0

Output:  

[1, 2, 13, 3, 4, 5, 6]

Ví dụ 4: Chèn một tuple vào danh sáchInserting a Tuple into the List

Ở đây chúng tôi đang chèn một tuple trong một danh sách bằng hàm chèn () trong python.

Python3

Các

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
9
[1, 2, 3, 4, 10, 5, 6, 7]
7 ________ 81 & nbsp;

[1, 2, (4, 5, 6), 3, 4, 5, 6]
7
[1, 2, 13, 3, 4, 5, 6]
5
[1, 2, 3, 4, 10, 5, 6, 7]
17

python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
2
[1, 2, 3, 4, 10, 5, 6, 7]
7 ________ 37 & nbsp;

Output:  

[1, 2, (4, 5, 6), 3, 4, 5, 6]

Cách tiếp cận hiệu quả hiệu suất nhất

Bạn cũng có thể chèn phần tử bằng cách sử dụng lập chỉ mục lát trong danh sách. Ví dụ:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

Để chèn nhiều phần tử lại với nhau tại một chỉ mục nhất định, tất cả những gì bạn cần làm là sử dụng

[1, 2, 3, 4, 10, 5, 6, 7]
20 của nhiều yếu tố mà bạn muốn chèn. Ví dụ:inserting multiple elements together at a given index, all you need to do is to use a
[1, 2, 3, 4, 10, 5, 6, 7]
20 of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

Để biết thêm về lập chỉ mục lát cắt, bạn có thể tham khảo: Hiểu ký hiệu lát cắt.

Lưu ý: Trong Python 3.x, sự khác biệt về hiệu suất giữa lập chỉ mục lát cắt và

[1, 2, 3, 4, 10, 5, 6, 7]
21 giảm đáng kể và cả hai đều gần như tương đương. Tuy nhiên, trong Python 2.x, sự khác biệt này khá đáng chú ý. Tôi đã chia sẻ so sánh hiệu suất sau trong câu trả lời này. In Python 3.x, difference of performance between slice indexing and
[1, 2, 3, 4, 10, 5, 6, 7]
21 is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Thay thế bằng cách sử dụng danh sách hiểu (nhưng rất chậm về mặt hiệu suất): (but very slow in terms of performance):

Thay vào đó, nó cũng có thể đạt được bằng cách sử dụng danh sách hiểu với

[1, 2, 3, 4, 10, 5, 6, 7]
22. (Nhưng xin đừng làm theo cách này. Nó chỉ là để minh họa):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

So sánh hiệu suất của tất cả các giải pháp

Đây là so sánh

[1, 2, 3, 4, 10, 5, 6, 7]
23 của tất cả các câu trả lời với danh sách 1000 yếu tố trên Python 3.9.1 và Python 2.7.16. Câu trả lời được liệt kê theo thứ tự hiệu suất cho cả hai phiên bản Python.

Python 3.9.1

  1. Câu trả lời của tôi bằng cách sử dụng chèn cắt lát - nhanh nhất (2,25 PhaSEC mỗi vòng)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Câu trả lời của Rushy Panchal với hầu hết các phiếu bầu bằng cách sử dụng

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. Câu trả lời được chấp nhận của Atoztoa dựa trên sự hợp nhất của các danh sách cắt lát - thứ ba (5,01 PhaSEC mỗi vòng)

    [1, 2, 3, 4, 10, 5, 6, 7]
    0
  4. Câu trả lời của tôi với danh sách hiểu và

    [1, 2, 3, 4, 10, 5, 6, 7]
    22 - thứ tư (rất chậm với 135 Lausc mỗi vòng)

    [1, 2, 3, 4, 10, 5, 6, 7]
    1

Python 2.7.16

  1. Câu trả lời của tôi bằng cách sử dụng chèn cắt lát - nhanh nhất (2.09 PhaSEC mỗi vòng)

    [1, 2, 3, 4, 10, 5, 6, 7]
    2
  2. Câu trả lời của Rushy Panchal với hầu hết các phiếu bầu bằng cách sử dụng

    [1, 2, 3, 4, 10, 5, 6, 7]
    3
  3. Câu trả lời được chấp nhận của Atoztoa dựa trên việc hợp nhất các danh sách cắt lát - thứ ba (4,44 Lausec mỗi vòng)

    [1, 2, 3, 4, 10, 5, 6, 7]
    4
  4. Câu trả lời của tôi với Danh sách Hiểu và

    [1, 2, 3, 4, 10, 5, 6, 7]
    22 - Thứ tư (rất chậm với 103 Lausc mỗi vòng)

    [1, 2, 3, 4, 10, 5, 6, 7]
    5

Làm thế nào để bạn thêm một phần tử vào một chỉ mục cụ thể trong Python?

Chèn (Index, ELEM) - Chèn phần tử tại chỉ mục đã cho, chuyển các phần tử sang phải.danh sách.Mở rộng (List2) thêm các yếu tố trong List2 vào cuối danh sách.Sử dụng + hoặc + = trên danh sách tương tự như sử dụng Extend (). -- inserts the element at the given index, shifting elements to the right. list. extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().

Làm thế nào để bạn thêm một phần tử vào một chỉ mục cụ thể?

Nếu chúng ta muốn thêm một phần tử vào vị trí thứ n, thì chỉ mục là (n - 1) chỉ mục ...
Bắt đầu → chỉ mục để chèn phần tử ..
Deletecount → 0 (vì chúng tôi không cần xóa bất kỳ yếu tố nào) ..
elem → các yếu tố để chèn ..

Làm thế nào để bạn thêm một phần tử vào một danh sách mảng tại một chỉ mục cụ thể trong Python?

Phương thức chèn () chèn một phần tử vào danh sách tại chỉ mục được chỉ định. inserts an element to the list at the specified index.

Làm thế nào để bạn thêm một chuỗi vào một vị trí cụ thể trong Python?

Sử dụng hàm nối (), nó có thể được sử dụng để thêm một ký tự trong một chuỗi ở vị trí mong muốn của chúng tôi.Trong ví dụ trên, chúng tôi chỉ định ký tự phân cách cho hàm nối () là một ký tự trống để tránh bất kỳ khoảng trống nào.