Wednesday, June 25, 2025

🐍 Arrays In Python - Definition, Example, Syntax and Types 🐍

 Follow me

Arrays in Python allow you to store multiple values in a single variable. Learn how to create arrays using lists, the array module, and NumPy.



🐬What is an Array?

An array is a linear data structure that stores elements in contiguous memory locations.
Each element is accessed using an index, and all elements are of the same data type.

🐬Key Features:

  • Fixed size (in most languages like C/C++)
  • Index-based access (starts from 0)
  • Efficient for reading elements
  • Stored in continuous memory

🐬Types of Arrays:

  • One-Dimensional Array: Simple list of elements
  • Two-Dimensional Array: Like a matrix (rows & columns)
  • Multi-Dimensional Array: 3D or more dimensions

🐬Array Syntax in Different Languages:

    🐒Python:

        arr = [10, 20, 30, 40]

        print(arr[2])  # Output: 30

    🐒C:

        int arr[4] = {10, 20, 30, 40};

        printf("%d", arr[2]); // Output: 30

    🐒C++:

        int arr[] = {10, 20, 30, 40};

        cout << arr[2]; // Output: 30

   πŸ’Java:

        int[] arr = {10, 20, 30, 40};

        System.out.println(arr[2]); // Output: 30

🐬Example Program (Python):

arr = [1, 2, 3, 4, 5]
 
    πŸŒ# Insert
        arr.insert(2, 99)  # at index 2
                print(arr)  # [1, 2, 99, 3, 4, 5]
 
    πŸŒ# Delete
         arr.remove(99)
                print(arr)  # [1, 2, 3, 4, 5]
 
    πŸŒ# Search
                print(3 in arr)  # True
 
    πŸŒ# Update
         arr[1] = 20
                print(arr)  # [1, 20, 3, 4, 5

🐬When to Use Arrays?

  • When the size is known in advance.
  • When you need fast access using index.
  • For storing elements of same type.




No comments:

Post a Comment

DSA using Python: Assignment - 2: Classes and Objects

Follow Me “In this assignment, we will learn how to use Python classes and objects to build reusable and structured code. The tasks cover re...