What is an Array?

On Social Media

An array is a data structure consisting of a collection of elements, each identified by an array index or key. Arrays are used to store multiple values in a single variable.

array

Characteristics of Arrays

  1. Fixed Size: The size of an array is fixed when it is created.
  2. Homogeneous Elements: All elements in an array are of the same type.
  3. Random Access: Array elements can be accessed directly using their index.

Basic Operations on Arrays

  1. Creation: Initialize an array.
# Create an array of integers
import array as arr

my_array = arr.array('i', [1, 2, 3, 4, 5])
print("Array:", my_array)

2. Traversal: Access each element of the array.

# Traverse the array
for element in my_array:
    print(element, end=' ')
print()

3. Insertion: Add an element at a specified position.

# Insert an element at the end
my_array.append(6)
print("Array after append:", my_array)

# Insert an element at a specific position
my_array.insert(2, 9)
print("Array after insertion:", my_array)

4. Deletion: Remove an element at a specified position.

# Remove an element by value
my_array.remove(9)
print("Array after removal:", my_array)

# Remove an element by index
deleted_element = my_array.pop(3)
print("Removed element:", deleted_element)
print("Array after pop:", my_array)

5. Searching: Find an element by its value.

# Search for an element
search_element = 4
index = my_array.index(search_element)
print(f"Element {search_element} found at index {index}")

6. Updating: Modify an element at a specified index.

# Update an element
my_array[0] = 10
print("Array after updating:", my_array)

On Social Media

Leave a Reply

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