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-8: Stack Extending List

This assignment is designed for practicing Stack implementation using Python by extending the built-in list class. It helps you learn how ...