In Python Adding elements to an array

Array

In python, an array is a data structure that holds multiple elements of the same type. Each value in the array is distinguished by its position, allowing for efficient storage and retrieval of data.

example:- Quiz scores

Here are some of the operations that can be performed on arrays.

  1. Adding elements to an array
  2. Removing elements from an array
  3. Sorting an array
  4. Reversing an array

The arrays are powerful data structure that can be used to store and manipulate the data. It data types of the same type collected at contiguous memory location.

Creation of array

In python, creating an array is simple.

#creating an empty array
empty_array=[]

#creating an array of strings
vegetables=['onion', 'cabbage', 'tomato', 'potato']

#Creating an array of numbers
numbers=[1,2,3,4,5]

In this example, ’empty_array’ represents empty array, ‘vegetables’ holds strings, and ‘numbers’ contains integers. Arrays are indicated by square brackets ‘[]’ with elements separated by the commas. Adding elements is performed for each data type.

Adding an elements to an array

In python, Adding elements to an array typically involves using the ‘append()’ method. The append() method can add the element into the array.

Here’s a simple program demonstrating how to add elements to a list using the append() method.

#Defining an empty list
my_list=[]

#adding elements to the list
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.append(5)

#printing the final list values
print("updated list:",my_list)

In the above program ‘my_list’ is an empty list, the ‘append()’ is the method.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top