Definition

  • In Python, arrays are collections that store multiple items of the same/different data type depending on the array type used in Python. 

Features

  • Unlike C or Java, Python has no built-in array data type. Instead, Python provides alternatives like lists and the array module for arrays.

Types of Array in Python

(A) Lists in Python
  • Lists are mutable dynamic structures and can store multiple elements of different data types, making them a common substitute for arrays in Python.
  • They are not as memory-efficient as real arrays when dealing with large datasets of uniform type.
  • This array is used for basic, flexible data structures and is defined using a [ ] symbol.
  • Unlike Tuple, they are mainly used when we want data to change in an application.
  • For example –
list1 = [10, 20, 30, 40, 50]  # This is the List of integers.
print(list1[0])  # Accessing the first element of list.
print(list1[2])  # Accessing the third element of list.
  • Features of Lists:
    • Lists can store multiple elements of different types.
    • The Lists elements are mutable (can change their elements).
    • The Lists can grow or shrink dynamically.
  • Common Operations and Methods Associated with the Lists:
    • Accessing the elements
      • print(list1[0])  # Accessing first element: 10
    • Appending an element
      • list1.append(60)  # [10, 20, 30, 40, 50, 60]
    • Inserting at a specific index
      • list1.insert(1, 70)  # [10, 70, 20, 30, 40, 50, 60]
    • Removing elements
      • list1.remove(70)  # [10, 20, 30, 40, 50, 60]
    • Slicing a list
      • print(list1[1:4])  # [20, 30, 40]
(B) Array Module in Python
  • Array Module is a basic array that is more memory efficient than lists but requires homogeneous data.
  • If we need an actual array in Python, the array module provides an array object that only stores elements of the same data type (e.g., integers, floats).
  • For importing the array Module, we use – import array.
  • For Examples –
import array
# To create an array of integers
array1 = array.array(‘i’, [1, 2, 3, 4, 5])
print(array1[0])  # Output: 1
  • Features of array Module
    • Arrays are more efficient than lists when working with large collections of the same data type.
    • It requires specifying the type of the array elements using type codes (e.g., ‘i’ for integers, ‘f’ for floats).
  • Common Type Codes in Array
Type Code C Type Python Type
'b' signed char int
'B' unsigned char int
'i' signed int int
'f' float float
'd' double float
  • Common Operations with Arrays
There are the following types of common operations in the Array Module –
    • Accessing elements
      • print(array1[1])  # Second element: 2
    • Appending an element
      • array1.append(6)  # array(‘i’, [1, 2, 3, 4, 5, 6])
    • Inserting at a specific index
      • array1.insert(2, 10)  # array(‘i’, [1, 2, 10, 3, 4, 5, 6])
    • Removing elements
      • array1.remove(10)  # array(‘i’, [1, 2, 3, 4, 5, 6])
  • Looping through array
    for x in array1:
        print(x)
    (C) NumPy Arrays (Advanced)
    • NumPy is a powerful library for handling large, multi-dimensional arrays with efficient mathematical operations in Python.
    • The NumPy library is often used in Python for more efficient and complex array operations.
    • NumPy provides multi-dimensional arrays and high-level mathematical functions unavailable in basic lists or the array module.
    • This array is used for high-performance numerical computation mainly.
    • For Installing NumPy

    pip install numpy

    • To Create a NumPy Array
    import numpy as np
    # Creating a 1D array
    arr = np.array([1, 2, 3, 4, 5])
    print(arr)  # Output: [1 2 3 4 5]
    # Creating a 2D array (matrix)
    matrix = np.array([[1, 2], [3, 4]])
    print(matrix)
    • Features of NumPy Arrays
      • Homogeneous: All elements in a NumPy array must be of the same type.
      • Supports multi-dimensional arrays (e.g., 2D arrays or matrices).
      • Optimized for numerical operations, making it much faster than lists for mathematical calculations.
    • Common NumPy Operations
      • Accessing elements
        • print(arr[0])  # Output: 1
      • Performing mathematical operations
        • print(arr * 2)  # Element-wise multiplication: [2 4 6 8 10]
    • Reshaping arrays: We can convert 1D into 2D as needed using NumPy Arrays.
      • array2 = arr.reshape(5, 1)  # Convert 1D array into 2D array with 5 rows and 1 column
    • Matrix multiplication using NumPy Array

    import numpy as np

    matrix1 = np.array([[1, 2], [3, 4]])
    matrix2 = np.array([[5, 6], [7, 8]])
    result = np.dot(matrix1, matrix2)
    print(result)  # Output: [[19 22] [43 50]]
    (D) Tuple in Python
    • Definition
      • Tuples in Python are immutable(not change), ordered collections of data items of the same/different type used when the user wants to group related data that should not be modified. 
    • Characteristics
      • They are Indexed, i.e. Like lists, tuple elements are accessed using indices starting from 0.
      • They are similar to lists, but unlike lists, tuples cannot be modified after they are created.
      • They are faster in operations((because of immutability) than Lists.
      • They are mainly used when we don’t want data to change in an application.
      • They offer efficient access to data and are often used in cases where immutability is essential, such as returning multiple values from functions or using them as dictionary keys.
    • Advantages 
      • Since Tuple is the ordered collection of items hence maintains the order of elements.
      • They are Heterogeneous i.e., Tuples can store elements of different data types (e.g., integers, strings, floats) as needed.
      • Tuples are often used to group related data, and their immutability can be useful when we want to ensure that certain data remains unchanged throughout a program.
    • Disadvantages 
      • They are immutable i.e., once a tuple is created, its contents cannot be changed (no adding, removing, or modifying elements). It may be advantageous in a few cases also.
    • To Create Tuples
      • We can create a tuple by enclosing values in parentheses `()` and separating them with commas.
      • For example –
        • x = (10, 20, 30, 40, 50)    # Tuple with same data types.
        • y= (10, “Hello India”, 3.141, True)    # Tuple with different data types/mix tuple/hybrid tuple.
        • z= (50,)  # Single element tuple (requires a trailing comma), without the comma, it’s just an integer.
        • k = ()   #Empty tuple
    • Accessing Tuple Elements
      • We can access individual elements of a tuple using indexing, or retrieve multiple elements using slicing.
      • For Example:
        • x = (10, 20, 30, 40, 50, 60, 70, 80, 90)
    # Accessing an element
    print(x[0])      # Output: 10 (first element)
    # Negative indexing
    print(x[-1])     # Output: 90 (last element)
    # Slicing a tuple
    print(x[1:5])   # Output: (20, 30, 40, 50)
    print(x[3:6])   # Output: (40, 50, 60)
        • Tuple is Immutable: Since tuples are immutable, we cannot change their content after creation. For example, trying to assign a new value to an index will raise an error. For example:-
    x = (1, 2, 3)
    x[0] = 10  # This will raise a TypeError: ‘tuple’ object does not support item assignment
        • Creating and accessing tuple elements
    person = (“Romi”, 25, “Doctor”)
    # Accessing tuple elements
    name = person[0]
    age = person[1]
    profession = person[2]
    print(f“Name: {name}, Age: {age}, Profession: {profession})
    # Output: Name: Romi, Age: 25, Profession: Doctor
    • Tuple Operations
      • Concatenation: We can concatenate two or more tuples using the `+` operator.
       tuple1 = (10, 20)
       tuple2 = (30, 40)
       result = tuple1 + tuple2
       print(result)  # Output: (10, 20, 30, 40)
      • Repetition: We can repeat the contents of a tuple using the `*` operator.
       x= (10, 20)
       print(x * 3)  # Output: (10, 20, 10, 20, 10, 20)
      • Membership Testing: We can check if an item is present in a tuple using the `in` keyword.
       x= (10, 20, 30, 40)
       print(30 in x)  # Output: True
       print(50 in x)  # Output: False
    • Tuple Methods

    Since tuples are immutable, hence they have comparatively only a few methods than Lists, mainly for querying.

      • count():
        • This method returns the number of occurrences of a specific value in the tuple.
        • For example –
     x = (10, 20, 30, 10, 10)
      print(x.count(10))  # Output: 3
      • index():
        • This method returns the index of the first occurrence of that specified value.
        • For example –
      x = (10, 20, 30, 40)
      print(x.index(30))  # Output: 2
    • Packing and Unpacking Tuples
      • Tuple Packing
        • The assignment of multiple values (of different types) to a tuple in a single statement is called packing.
        • For example –
    x = 1, 2, “apple”, 3.5      # Parentheses are optional
    print(x)    # Output: (1, 2, ‘apple’, 3.5)
      • Tuple Unpacking
        • We can also unpack a tuple into individual variables.
        • For example – 
    x = 1, 2, “apple”, 3.5   
    a, b, c, d = x
    print(a)  # Output: 1
    print(b)  # Output: 2
    print(c)  # Output: apple
    print(d)  # Output: 3.5
        • Unpacking with a wildcard (`*`): We can use `*` to unpack the remaining values into a list.
      x = (10, 20, 30, 40, 50)
      a, b, *rest = x
      print(a)  # Output: 10
      print(b)  # Output: 20
      print(rest)  # Output: [30, 40, 50]
    • Use of Tuples
      • Return Multiple Values from Functions
        • Tuples are often used to return multiple values from a function.
        • For example –
    def Method1():
    return (30, 70)
       temp, humidity = Method1()     #assigns two values
      • Immutable Grouping of Related Data
        • If we want to group related items and ensure they don’t change, a tuple is used.
        • user_profile = (“Rani”, 18, “Student”)
      • Keys in Dictionaries:
        • Tuples can be used as keys in dictionaries, whereas lists cannot because tuples are immutable and washable.
        • For example – 

       my_dict = {(1, 2): “Point A”, (3, 4): “Point B”}

    Loading

    Categories: Python Theory

    0 Comments

    Leave a Reply

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

    This site uses Akismet to reduce spam. Learn how your comment data is processed.