Adding Array Items in Python: Appending Elements to Arrays

thumb_up 1  ·  sell Python array item addition, Appending elements to Python arrays, Adding items to a Python array

The append() Method

The append() method adds a new element at the end of given array.

Syntax

array.append(v)

Parameters

  • v − new value is added at the end of the array. The new value must be of the same type as datatype argument used while declaring array object.

Example

 
import array as arr a = arr.array('i', [1, 2, 3]) a.append(10) print (a)

It will produce the following output −

array('i', [1, 2, 3, 10])

The insert() Method

The array class also defines insert() method. It is possible to insert a new element at the specified index.

Syntax

array.insert(i, v)

Parameters

  • i − The index at which new value is to be inserted.

  • v − The value to be inserted. Must be of the arraytype.

Example

 
import array as arr a = arr.array('i', [1, 2, 3]) a.insert(1,20) print (a)

It will produce the following output −

array('i', [1, 20, 2, 3])

The extend() Method

The extend() method in array class appends all the elements from another array of same typecode.

Syntax

array.extend(x)

Parameters

  • x − Object of array.array class

Example

 
import array as arr a = arr.array('i', [1, 2, 3, 4, 5]) b = arr.array('i', [6,7,8,9,10]) a.extend(b) print (a)

It will produce the following output −

array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])




The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.

Was dit antwoord nuttig?

Gerelateerde artikelen

description

Exploring Python's Key Characteristic

Python is a feature rich high-level, interpreted, interactive and object-oriented scripting language. This tutorial will list down some of…

arrow_forward
description

Comparing Python and C++

Both Python and C++ are among the most popular programming languages. Both of them have their advantages and disadvantages. In this…

arrow_forward
description

Creating a Python Hello World Program

This tutorial will teach you how to write a simple Hello World program using Python Programming language. This program will make use of…

arrow_forward
description

Python's Versatile Application Domains

Python is a general-purpose programming language. It is suitable for development of wide range of software applications. Over last few…

arrow_forward
description

Understanding the Python Interpreter

Python is an interpreter-based language. In a Linux system, Python's executable is installed in /usr/bin/ directory. For Windows, the…

arrow_forward
arrow_back « Terug