Introduction
To adhd to an array successful Python, you append, extend, aliases insert elements depending connected the building you use. Most tutorials mean a Python list when they opportunity “array.” For typed numeric storage, usage the stdlib array module. For mathematics on multi-dimensional data, usage NumPy.
nums = [1, 2, 3] nums.append(4) # 1 point astatine the end nums.extend([5, 6]) # galore items astatine the end nums.insert(0, 0) # 1 point astatine an index print(nums) # [0, 1, 2, 3, 4, 5, 6]This guideline covers lists, the array module, and NumPy. You will spot erstwhile to pick each type, really to adhd elements successful a loop, and really to debar communal production errors.
Deploy your Python applications from GitHub using DigitalOcean App Platform. Let DigitalOcean attraction connected scaling your app.
Key takeaways
- Lists are the default “array” successful Python. Use append() for 1 item, extend() for many, and insert() for a circumstantial index.
- The array module stores 1 numeric type per array. append(), extend(), and insert() activity for illustration lists, and + joins 2 arrays into a caller object.
- NumPy returns a new array from numpy.append() and numpy.insert(). The original array stays unchanged.
- append() vs extend(): append() adds 1 object. extend() unpacks an iterable and adds each value. Mixing them up creates nested lists.
- Shape matters for 2D NumPy arrays. Row and file widths must lucifer along the axis you choose, aliases Python raises ValueError.
- For repeated maturation successful loops, extend() aliases numpy.concatenate() beat many single-item appends connected ample information sets.
- Tuples are immutable. Convert to a database earlier you adhd elements.
Prerequisites
- Python 3 on your instrumentality aliases a Droplet.
- Basic familiarity with Python lists and importing modules.
- Optional: NumPy. Install pinch pip instal numpy aft you group up your environment. See the NumPy instal guide.
Python database vs array module vs NumPy
| list | Built-in | Yes | General sequences, APIs, mixed data |
| array.array | stdlib array | No | Compact numeric buffers |
| numpy.ndarray | NumPy | No | Math, ML, multi-dimensional data |
Note: You only adhd elements of the aforesaid information type to an array.array object. You only subordinate 2 array.array objects pinch matching type codes.
Add elements to a Python list
Most “add to array” searches target lists. Lists are mutable and judge mixed types. See Python Add to List for a afloat walkthrough.
| append(x) | Adds 1 point to the end | nums.append(4) |
| extend(iterable) | Adds each point from an iterable | nums.extend([5, 6]) |
| insert(i, x) | Inserts 1 point earlier scale i | nums.insert(0, 10) |
| + operator | Returns a caller mixed list | nums = a + b |
For list-specific methods, see How to Use List Methods successful Python 3.
Add elements successful a loop
You often build a series while iterating. append() adds 1 worth per trip through the loop. extend() adds a batch erstwhile you already person a collection.
squares = [] for n in range(5): squares.append(n ** 2) print(squares) # [0, 1, 4, 9, 16]For a compact alternative, usage a list comprehension:
squares = [n ** 2 for n in range(5)] print(squares) # [0, 1, 4, 9, 16]Inside a for loop, call extend() erstwhile each loop produces aggregate values:
rows = [] for brace in [(1, 2), (3, 4)]: rows.extend(pair) print(rows) # [1, 2, 3, 4]Adding elements pinch the array module
The array module stores integers, floats, aliases different numeric codes successful a compact buffer. You subordinate arrays pinch + or mutate successful spot pinch append(), extend(), and insert().
| + operator, x + y | Returns a caller array pinch elements from some arrays |
| append(x) | Adds a azygous constituent to the end |
| extend(iterable) | Adds items from a list, array, aliases different iterable |
| insert(i, x) | Inserts an constituent earlier scale i |
The pursuing illustration creates a caller array by joining 2 arrays:
import array arr1 = array.array('i', [1, 2, 3]) arr2 = array.array('i', [4, 5, 6]) print("arr1 is:", arr1) print("arr2 is:", arr2) arr3 = arr1 + arr2 print("After arr3 = arr1 + arr2, arr3 is:", arr3)The output is:
Output
arr1 is: array('i', [1, 2, 3]) arr2 is: array('i', [4, 5, 6]) After arr3 = arr1 + arr2, arr3 is: array('i', [1, 2, 3, 4, 5, 6])The adjacent illustration adds elements pinch append(), extend(), and insert():
import array arr1 = array.array('i', [1, 2, 3]) arr2 = array.array('i', [4, 5, 6]) print("arr1 is:", arr1) print("arr2 is:", arr2) arr1.append(4) print("\nAfter arr1.append(4), arr1 is:", arr1) arr1.extend(arr2) print("\nAfter arr1.extend(arr2), arr1 is:", arr1) arr1.insert(0, 10) print("\nAfter arr1.insert(0, 10), arr1 is:", arr1)The output is:
Output
arr1 is: array('i', [1, 2, 3]) arr2 is: array('i', [4, 5, 6]) After arr1.append(4), arr1 is: array('i', [1, 2, 3, 4]) After arr1.extend(arr2), arr1 is: array('i', [1, 2, 3, 4, 4, 5, 6]) After arr1.insert(0, 10), arr1 is: array('i', [10, 1, 2, 3, 4, 4, 5, 6])Each method runs connected arr1 and changes the original object.
Adding elements to a NumPy array
NumPy provides numpy.append() and numpy.insert() for adding values. Both return a copy. Neither changes the root array. For predominant updates, prefer numpy.concatenate() or pre-allocate pinch numpy.zeros() and delegate by index.
| numpy.append(...) | Appends to a copy. axis=None flattens both. |
| numpy.insert(...) | Inserts earlier index. axis=None flattens arr. |
numpy.append() calls numpy.concatenate() internally. See array manipulation routines in the NumPy docs. For a focused guide, read NumPy Append successful Python.
Note: Install NumPy earlier you tally the examples successful this section. Follow the NumPy instal guide.
The examples beneath usage 2D arrays to show really the axis statement changes the result. Test them successful the Python interactive console.
Appending pinch numpy.append()
NumPy arrays person a style (rows, columns for 2D data). When you append on an axis, widths on the different dimensions must match.
array([[1, 2], [3, 4]]) has style (2, 2). array([[10, 20, 30], [40, 50, 60]]) has style (2, 3).
Import NumPy, past create and people np_arr1:
- import numpy arsenic np
- np_arr1 = np.array([[1, 2], [3, 4]])
- print(np_arr1)
Output
[[1 2] [3 4]]Check the style of np_arr1:
- np_arr1.shape
Output
(2, 2)Create and people np_arr2:
- np_arr2 = np.array([[10, 20, 30], [40, 50, 60]])
- print(np_arr2)
Output
[[10 20 30] [40 50 60]]Append np_arr2 to np_arr1 on axis 0 (by row):
- np.append(np_arr1, np_arr2, axis=0)
You get a ValueError because the file counts disagree (2 vs 3):
Output
Traceback (most caller telephone last): ... ValueError: each the input array dimensions for the concatenation axis must match exactly, but on magnitude 1, the array astatine scale 0 has size 2 and the array astatine scale 1 has size 3Append on axis 1 (by column) instead:
- np.append(np_arr1, np_arr2, axis=1)
Output
array([[ 1, 2, 10, 20, 30], [ 3, 4, 40, 50, 60]])When some arrays stock the aforesaid statement count, axis 1 works.
This book shows each 3 axis modes:
import numpy as np np_arr1 = np.array([[1, 2], [3, 4]]) np_arr2 = np.array([[10, 20], [30, 40]]) print("np_arr1 is:\n", np_arr1) print("np_arr2 is:\n", np_arr2) append_axis_none = np.append(np_arr1, np_arr2, axis=None) print("append_axis_none is:\n", append_axis_none) append_axis_0 = np.append(np_arr1, np_arr2, axis=0) print("append_axis_0 is:\n", append_axis_0) append_axis_1 = np.append(np_arr1, np_arr2, axis=1) print("append_axis_1 is:\n", append_axis_1)The output is:
Output
np_arr1 is: [[1 2] [3 4]] np_arr2 is: [[10 20] [30 40]] append_axis_none is: [ 1 2 3 4 10 20 30 40] append_axis_0 is: [[ 1 2] [ 3 4] [10 20] [30 40]] append_axis_1 is: [[ 1 2 10 20] [ 3 4 30 40]]With axis=0, rows stack. With axis=1, columns join. With axis=None, both arrays flatten into 1 1D result.
Inserting pinch numpy.insert()
numpy.insert() places values earlier a fixed scale on an axis and returns a new array. When axis=None, only the first array flattens. The values to insert keep their style unless you walk an axis.
import numpy as np np_arr1 = np.array([[1, 2], [4, 5]]) np_arr2 = np.array([[10, 20], [30, 40]]) np_arr3 = np.array([100, 200, 300]) print("np_arr1 is:\n", np_arr1) print("np_arr2 is:\n", np_arr2) print("np_arr3 is:\n", np_arr3) insert_axis_none = np.insert(np_arr1, 1, np_arr3, axis=None) print("insert_axis_none is:\n", insert_axis_none) insert_axis_0 = np.insert(np_arr1, 1, np_arr2, axis=0) print("insert_axis_0 is:\n", insert_axis_0) insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1) print("insert_axis_1 is:\n", insert_axis_1)The output is:
Output
np_arr1 is: [[1 2] [4 5]] np_arr2 is: [[10 20] [30 40]] np_arr3 is: [100 200 300] insert_axis_none is: [ 1 100 200 300 2 4 5] insert_axis_0 is: [[ 1 2] [10 20] [30 40] [ 4 5]] insert_axis_1 is: [[ 1 10 30 2] [ 4 20 40 5]]When you insert a 2D array on axis 1, each statement of the inserted array becomes a abstracted column. Wrap the scale successful quadrate brackets to insert the full artifact at once:
import numpy as np np_arr1 = np.array([[1, 2], [3, 4]]) np_arr2 = np.array([[10, 20], [30, 40]]) print("np_arr1 is:\n", np_arr1) print("np_arr2 is:\n", np_arr2) insert_axis_1 = np.insert(np_arr1, 1, np_arr2, axis=1) print("insert_axis_1 is:\n", insert_axis_1) insert_index_axis_1 = np.insert(np_arr1, [1], np_arr2, axis=1) print("insert_index_axis_1 is:\n", insert_index_axis_1)The output is:
Output
np_arr1 is: [[1 2] [3 4]] np_arr2 is: [[10 20] [30 40]] insert_axis_1 is: [[ 1 10 30 2] [ 3 20 40 4]] insert_index_axis_1 is: [[ 1 10 20 2] [ 3 30 40 4]]insert_axis_1 interleaves columns. insert_index_axis_1 places the afloat np_arr2 block earlier file scale 1.
append() vs extend()
| append() | One entity (the full list) | [1, 2, 3, [4, 5, 6]] |
| extend() | Each point from the iterable | [1, 2, 3, 4, 5, 6] |
This quality applies to lists and to array.array objects. See Concatenate Lists successful Python when you request to subordinate sequences without mutation.
Performance comparison
| list.append() | One constituent astatine end | O(1) | Single items successful a loop |
| list.extend() | Many elements astatine once | O(k) | Iterable batches |
| list.insert() | Insert astatine index | O(n) | Small lists |
| array.append() | One typed element | O(1) | stdlib numeric buffers |
| numpy.append() | New array pinch values | O(n) | Rare one-off joins |
| numpy.insert() | New array pinch insert | O(n) | Rare indexed inserts |
| numpy.concatenate() | Join on axis | O(n) | Repeated NumPy growth |
For ample NumPy workloads, debar numpy.append() wrong tight loops. Build a list of arrays and telephone numpy.concatenate() once, aliases pre-allocate the target array.
import timeit # append() successful a loop start = timeit.default_timer() lst = [] for one in range(10000): lst.append(i) t_append = timeit.default_timer() - start # extend() once start = timeit.default_timer() lst = [] lst.extend(range(10000)) t_extend = timeit.default_timer() - start print(f"append loop: {t_append:.6f}s") print(f"extend once: {t_extend:.6f}s")extend() typically finishes faster than thousands of append() calls because Python grows the soul buffer successful less steps.
Common errors and debugging
Using append() alternatively of extend() for aggregate elements
append() treats the iterable arsenic a azygous object:
arr = [1, 2, 3] arr.append([4, 5, 6]) print(arr) # [1, 2, 3, [4, 5, 6]]Use extend() to flatten the values in:
arr = [1, 2, 3] arr.extend([4, 5, 6]) print(arr) # [1, 2, 3, 4, 5, 6]Type mismatch pinch NumPy arrays
NumPy arrays clasp 1 dtype. Adding floats to an integer array upgrades the dtype:
import numpy as np arr = np.array([1, 2, 3], dtype=int) arr = np.append(arr, [4.5, 6.7]) print(arr) # [1. 2. 3. 4.5 6.7] print(arr.dtype) # float64Pass matching types, aliases formed first:
import numpy as np arr = np.array([1, 2, 3], dtype=int) arr = np.append(arr, [4, 6]) print(arr) # [1 2 3 4 6] print(arr.dtype) # int64Adding elements to a tuple
Tuples are immutable. append() raises AttributeError:
my_tuple = (1, 2, 3) my_tuple.append(4) # AttributeErrorConvert to a list, add, and person backmost if you request a tuple:
my_list = list((1, 2, 3)) my_list.append(4) my_tuple = tuple(my_list) print(my_tuple) # (1, 2, 3, 4)FAQs
1. How do I adhd an constituent to the extremity of an array successful Python?
For a list, telephone append():
nums = [1, 2, 3] nums.append(4) print(nums) # [1, 2, 3, 4]For array.array, the telephone is the same:
import array arr = array.array('i', [1, 2, 3]) arr.append(4) print(arr) # array('i', [1, 2, 3, 4])For NumPy, delegate to a caller adaptable because numpy.append() returns a copy:
import numpy as np arr = np.array([1, 2, 3]) arr = np.append(arr, 4) print(arr) # [1 2 3 4]2. What is the quality betwixt append() and extend() successful Python?
append() adds 1 object. extend() walks an iterable and adds each value. Passing a database to append() nests the list. Passing the aforesaid database to extend() flattens the values into the genitor sequence.
3. How do I adhd an constituent astatine a circumstantial scale successful Python?
Call insert(index, value) connected a database aliases array.array:
nums = [10, 30, 40] nums.insert(1, 20) print(nums) # [10, 20, 30, 40]For NumPy, usage numpy.insert() and shop the returned array:
import numpy as np arr = np.array([10, 30, 40]) arr = np.insert(arr, 1, 20) print(arr) # [10 20 30 40]4. What is the quality betwixt a Python database and an array?
A database is simply a built-in sequence. An array.array holds 1 numeric type and uses less representation for ample numeric buffers. A NumPy ndarray adds vectorized mathematics and fixed dtype rules. Lists judge mixed types for illustration strings and integers successful the same sequence. Arrays and NumPy ndarrays do not.
5. How do I adhd elements to an array successful a loop?
Call append() erstwhile per value, aliases extend() erstwhile each loop produces a batch:
evens = [] for n in range(10): if n % 2 == 0: evens.append(n) print(evens) # [0, 2, 4, 6, 8]For NumPy, cod arrays successful a database and concatenate erstwhile alternatively of repeated numpy.append() calls.
Conclusion
You now cognize really to adhd to an array successful Python crossed 3 structures: lists, the array module, and NumPy. You compared append(), extend(), and insert(), saw really axis arguments style NumPy output, and reviewed predominant mistakes for new and knowledgeable developers.
What’s next
Keep building pinch these Python tutorials:
- Python Add to List
- NumPy Append successful Python
- Python Convert NumPy Array to List
- Concatenate Lists successful Python
- Python Pandas Module Tutorial
Run information scripts connected DigitalOcean App Platform or GPU-backed Droplets without managing hardware. For AI workloads, research the DigitalOcean AI Platform.
This activity is licensed nether a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
English (US) ·
Indonesian (ID) ·