Home >Backend Development >Python Tutorial >How to add elements to one-dimensional array in python

How to add elements to one-dimensional array in python

尚
Original
2019-06-28 11:22:3117204browse

How to add elements to one-dimensional array in python

An array is an ordered collection in which elements can be added and removed at any time. You can use the append() function to add new objects to the end of the array. You can also use the insert() function to insert a specified object into a specified position in the array.

1. append() function:

append() function syntax:

list.append(obj)

Parameters: obj -- the object added to the end of the list.

Return value: This method has no return value, but it will modify the original list.

The following example shows how to use the append() function:

aList = [123, 'xyz', 'zara', 'abc'];
aList.append( 2009 );
print "Updated List : ", aList;

The output results are as follows:

Updated List :  [123, 'xyz', 'zara', 'abc', 2009]

2. insert() function:

Syntax:

list.insert(index, obj)

Parameters:

index -- The index position where object obj needs to be inserted. obj – the object to be inserted into the list.

Return value: This method has no return value, but will insert the object at the specified position in the list.

The following example shows how to use the insert() function:

aList = [123, 'xyz', 'zara', 'abc'] 
aList.insert( 3, 2009) 
print "Final List : ", aList

Output result:

Final List : [123, 'xyz', 'zara', 2009, 'abc']

For more Python related technical articles, please visit Python Tutorial column for learning!

The above is the detailed content of How to add elements to one-dimensional array in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn