Add Elements to Python Array {3 Methods} (2024)

Introduction

Adding elements is a basic operation with Python arrays. There are multiple ways to define arrays in Python, such as with lists (an array-like data structure), the array module, or the NumPy library. Each method has different ways to add new elements.

Depending on the array type, there are different methods to insert elements.

This article shows how to add elements to Python arrays (lists, arrays, and NumPy arrays).

Add Elements to Python Array {3 Methods} (1)

Prerequisites

  • Python 3 installed.
  • An IDE or text editor to write and edit code.
  • An IDE or command line/terminal to run code.
  • (optional) NumPy installed.

How to Add Elements to a Python Array?

Python lists act as array-like data structures that allow different element types. On the other hand, thearrayandNumPylibraries offer modules to create traditional arrays.

The methods to add an element to an array differ depending on the data type. Below is an overview of several possible methods.

Method 1: Adding to an Array in Python by Using Lists

If using lists as arrays, Python offers several built-in methods to add one or more elements to an existing list. The methods are:

  • The (+) operator
  • append()
  • extend()
  • insert()

Below is an overview of the three different methods with examples.

1. Add one or more elements to the end of a list with the (+) operator. The operator adds a single value or another list (or iterable) to an existing list and updates the original variable.

To append one element to a list, see the following example:

l = [1, 2, 3]print("List before adding:", l)l = l + ["four"]print("List after adding:", l)
Add Elements to Python Array {3 Methods} (2)

Alternatively, append multiple elements:

l = [1, 2, 3]print("List before adding:", l)l = l + ["four", "five", "six"]print("List after adding:", l)
Add Elements to Python Array {3 Methods} (3)

The operator appends the elements to the end of the original list and increases the list length.

Note: Read our article and find out how to append a string in Python.

2. Add a single element to the end of a list with the built-in append() method. The method does not support adding multiple values to a list.

For example, the code below shows how to create a list and append an element:

l = [1, 2, 3]print("List before appending:", l)l.append("four")print("List after appending:", l)
Add Elements to Python Array {3 Methods} (4)

The original list contains the new element at the end.

3. Add one or more elements to the end of a list with the built-in extend() method. Provide a new list (or another iterable) as the method's parameter.

The example below shows how to add a new list to an existing one:

l = [1, 2, 3]print("List before extending:", l)l.extend(["four", "five", "six"])print("List after extending:", l)
Add Elements to Python Array {3 Methods} (5)

The old list extends with the new elements, which all append to the end of the list.

4. Add an element to an exact location in a list with the insert() method. Provide the location index and the value to insert.

For example:

l = [1, 2, 3]print("List before inserting:", l)l.insert(1, 1.5)print("List after inserting:", l)
Add Elements to Python Array {3 Methods} (6)

The new element inserts at the provided index, while all the following values shift to the right by one index.

Method 2: Adding to an Array in Python by Using Array Module

The Python array module mimics traditional arrays, where all elements are restricted to the same data type. The module is similar to lists when it comes to adding new elements. The possible methods are:

  • + operator
  • append()
  • extend()
  • insert()

Below is a brief overview of each method using the array module.

1. Add one or more elements to an array using the + operator. The element(s) append to the end.

The example below shows how to add to an array with the + operator:

import arraya = array.array('i', [1,2,3])print("Array before adding:", a)b = array.array('i', [4,5,6])a = a + bprint("Array after adding", a)
Add Elements to Python Array {3 Methods} (7)

Both arrays use the same type code ('i'for unsigned integer). The+operator appends the new set of numbers to the existing one.

2. Add a single element to an array with the append() method. The method appends a new value to the end, which must match the array element type.

See the following example to use the append() function to add a new element to an array:

import arraya = array.array('i', [1,2,3])print("Array before appending:", a)a.append(4)print("Array after appending:", a)
Add Elements to Python Array {3 Methods} (8)

The method extends the existing list with a new element, which matches the array type code.

3. Add one or more elements to an array end with the extend() method. Provide the elements in an iterable data type. The items in the iterable must match the array's data type.

For example, add multiple elements to an array with a Python list:

import arraya = array.array('i', [1,2,3])print("Array before extending:", a)a.extend([4,5,6])print("Array after extending:", a)
Add Elements to Python Array {3 Methods} (9)

The extend() method links the list to the array.

4. Add an element to a specific place in an array with the insert() method. Set the element index and provide the element value to insert the value.

For example:

import arraya = array.array('i', [1,2,3])print("Array before inserting:", a)a.insert(1,0)print("Array after inserting:", a)
Add Elements to Python Array {3 Methods} (10)

The value 0 inserts at index 1, pushing all the following elements to the right.

Method 3: Adding to NumPy Array

The NumPy library contains an array type suitable for numerical calculations. Unlike lists and arrays, fewer ways exist to add elements to a NumPy array. The methods are:

  • append()
  • insert()

Both methods work as functions that require the array and appended values.

Below are explanations and examples of both methods for inserting elements into a NumPy array.

1. Use the append() method to add one or more elements to a copy of a NumPy array. Provide the original variable and add the new values to an iterable.

For example:

import numpy as npn = np.array([1, 2, 3])print("NumPy array before appending:", n)n = np.append(n, [4, 5, 6])print("NumPy array after appending:", n)
Add Elements to Python Array {3 Methods} (11)

The append() method adds a list to the NumPy array and overwrites the old variable with new values.

2. Use the insert() method to add one element at a specific location to a copy of a NumPy array. Provide the NumPy array, index, and value to add a new element.

For example:

import numpy as npn = np.array([1,2,3])print("NumPy array before inserting:", n)n = np.insert(n,1,0)print("NumPy array after inserting:", n)
Add Elements to Python Array {3 Methods} (12)

The method inserts a new value (0) at index 1 and pushes all following values by one to the right.

Conclusion

After reviewing the methods from this guide, you know how to add an element to an array.

Whether you're working with lists, arrays, or NumPy arrays, Python offers several methods for each data type to insert new values.

Add Elements to Python Array {3 Methods} (2024)
Top Articles
Effective assessment
Preparing for an Evaluation - Guidelines and Tools for Pre-Evaluation Planning - Resource
Where To Go After Howling Pit Code Vein
Skyward Sinton
Craglist Oc
Caroline Cps.powerschool.com
Hotels Near 500 W Sunshine St Springfield Mo 65807
Flights to Miami (MIA)
Mawal Gameroom Download
Evita Role Wsj Crossword Clue
Joe Gorga Zodiac Sign
Www.paystubportal.com/7-11 Login
Keurig Refillable Pods Walmart
Hope Swinimer Net Worth
About Us | TQL Careers
Mini Handy 2024: Die besten Mini Smartphones | Purdroid.de
2015 Honda Fit EX-L for sale - Seattle, WA - craigslist
Best Suv In 2010
Unlv Mid Semester Classes
24 Hour Drive Thru Car Wash Near Me
2020 Military Pay Charts – Officer & Enlisted Pay Scales (3.1% Raise)
Lehmann's Power Equipment
Royal Cuts Kentlands
Teacup Yorkie For Sale Up To $400 In South Carolina
Lisas Stamp Studio
Understanding Gestalt Principles: Definition and Examples
Drift Hunters - Play Unblocked Game Online
Barista Breast Expansion
Villano Antillano Desnuda
Ts Modesto
Does Royal Honey Work For Erectile Dysfunction - SCOBES-AR
Ff14 Sage Stat Priority
Shauna's Art Studio Laurel Mississippi
Magicseaweed Capitola
10 games with New Game Plus modes so good you simply have to play them twice
Labyrinth enchantment | PoE Wiki
„Wir sind gut positioniert“
Google Flights Orlando
Exploring the Digital Marketplace: A Guide to Craigslist Miami
Craigslist Minneapolis Com
Sound Of Freedom Showtimes Near Amc Mountainside 10
Rocket Lab hiring Integration & Test Engineer I/II in Long Beach, CA | LinkedIn
Sherwin Source Intranet
Iron Drop Cafe
300+ Unique Hair Salon Names 2024
Rocket Bot Royale Unblocked Games 66
Minecraft Enchantment Calculator - calculattor.com
The Missile Is Eepy Origin
Ff14 Palebloom Kudzu Cloth
211475039
The Love Life Of Kelsey Asbille: A Comprehensive Guide To Her Relationships
Latest Posts
Article information

Author: Neely Ledner

Last Updated:

Views: 5604

Rating: 4.1 / 5 (62 voted)

Reviews: 93% of readers found this page helpful

Author information

Name: Neely Ledner

Birthday: 1998-06-09

Address: 443 Barrows Terrace, New Jodyberg, CO 57462-5329

Phone: +2433516856029

Job: Central Legal Facilitator

Hobby: Backpacking, Jogging, Magic, Driving, Macrame, Embroidery, Foraging

Introduction: My name is Neely Ledner, I am a bright, determined, beautiful, adventurous, adventurous, spotless, calm person who loves writing and wants to share my knowledge and understanding with you.