Python Array Module

Python Array Module

In Python, arrays are primarily handled using lists, but Python also provides the array module for creating arrays of a fixed type. Here is how you can use the Python array module to perform operations.

1. Importing the array module
Before using arrays in Python, you need to import the array module:
Syntax:
import array
Example:

import array

2. Creating an Array:
You need to define the type and the values when creating an array. In Python, you use a type code to specify the type of the array.
Syntax:
import array

# Creating an array
array_name = array.array(typecode, [list])

Components:
    ● array_name: This is the variable name that will hold the array object you are creating. You can name it anything
       you prefer.
    ● array.array: This is a function call from the array module to create a new array object.
    ● typecode: This is a single character that specifies the type of elements that the array will store. Different
       typecodes correspond to different data types. For example:
          ○ ‘i’: Signed integer.
          ○ ‘f’: Floating-point number.
          ○ ‘d’: Double-precision floating-point number.
          ○ ‘b’: Signed char.
          ○ ‘u’: Unicode character (Python 2.x; use ‘str’ in Python 3.x).

● [initializer_list]: This is an optional argument that can be a list (or any iterable) used to initialize the array with values. If this list is provided, the array will be created with those initial values. If omitted, an empty array will be created.
Example initializer lists can be [1, 2, 3], [3.5, 4.5, 5.5], etc.

Example:

import array

# Create an array of integers
numbers = array.array(‘i’, [4, 2, 8, 1, 6])

3. Commonly Used Operations in array module
Sorting an Array
Python doesn’t have a direct method for sorting arrays, but you can convert the array to a list, sort it, and convert it back if needed.
Example:

import array
numbers = array.array(‘i’, [4, 2, 8, 1, 6])
numbers_list = sorted(numbers)

# Print sorted array
for item in numbers_list:
      print(item, end=’ ‘) # Output: 1 2 4 6 8

Iterating Over an Array
You can use the for loop in Python to iterate over an array and perform actions on each element.
Example:

numbers = array.array(‘i’, [10, 20, 30, 40, 50])
for n in numbers:
      print(n * 2) # Output: 20, 40, 60, 80, 100

Copying Arrays
In Python, you can copy arrays by using slicing or the copy() method (if you convert it to a list first).
Example:

source = array.array(‘i’, [40, 35, 70, 20, 55])
destination = array.array(‘i’, source[:4]) # Copy first 4 elements

for item in destination:
      print(item) # Output: 40, 35, 70, 20

Comparing Arrays
In Python, arrays are compared using == for element-wise comparison.
Example:

first_array = array.array(‘i’, [40, 20, 30, 45])
second_array = array.array(‘i’, [40, 30, 20, 45])
are_equal = first_array == second_array

print(are_equal) # Output: False (as the arrays are not equal)

Converting Array to List
Arrays have a fixed size, but lists are dynamic. You can easily convert an array to a list in Python.

numbers_array = array.array(‘i’, [10, 20, 30, 40, 50])
numbers_list = list(numbers_array)

# Modify the list
numbers_list.append(25)
numbers_list.remove(20)

# Print the list elements
print(“List elements:”)
for number in numbers_list:
    print(number, end=’ ‘)
#Output:10 30 40 50 25

4. A simple example of using an array with an if-else statement. In this example, we’ll create an array of numbers and check if each number is even or odd using an if-else statement.
Example:

numbers = array.array(‘i’, [10, 5, 8, 3, 12])
for num in numbers:
    if num % 2 == 0:
          print(f”{num} is even.”)
    else:
          print(f”{num} is odd.”)
”’
Output:
10 is even.
5 is odd.
8 is even.
3 is odd.
12 is even.
”’

Explanation:
● numbers = array.array(‘i’, [10, 5, 8, 3, 12]): Defines an array of integers with specific values.
● for num in numbers:: Iterates through each element in the array.
● if num % 2 == 0:: Checks if the number is even.
● print(f”{num} is even.”): Prints that the number is even.
● else:: If the number is not even.
● print(f”{num} is odd.”): Prints that the number is odd.

Course Video

Course Video English:

Task:

1. Sort an Array:
Create an integer array with the values {3, 1, 4, 1, 5, 9}. Sort the array and print the sorted values.

2. Double Each Element:
Create an integer array with the values {1, 2, 3, 4, 5}. Double each element and print the modified array.

3. Copy Array:
Create a source integer array with the values {11, 22, 33, 44, 55}. Create a destination array of size 3. Copy the first 3 elements from the source to the destination and print the destination array.

4. Check Equality:
Create two integer arrays, one with the values {5, 10, 15} and the other with the values {5, 10, 15}. Check if the arrays are equal and print the result.

5. Even or Odd Check:
Create an integer array with the values {7, 14, 21, 28, 35}. Use a for loop and an if-else statement to check if each number is even or odd, and print the result.

6. Sort and Print Strings:
Create a string array with the values {“banana”, “apple”, “cherry”}. Sort the array alphabetically and print the sorted values.

7. Find and Print Even Numbers:
Create an integer array with the values {12, 15, 18, 21, 24}. Use a for loop and an if-else statement to print only the even numbers from the array.

Task Video

YouTube Reference :

Frequently Asked Questions

Still have a question?

Let's talk

It is used to exit a loop prematurely when a certain condition is met.

break: Exits the loop.,continue: Skips the current iteration and moves to the next.,pass: Does nothing and is used as a placeholder.

Use the break statement inside a loop to terminate it early.

A debugging tool to pause program execution at a specific line.

break: Stops a loop.,return: Exits a function and optionally returns a value.

Skips the rest of the current loop iteration and moves to the next one.

It is the continue keyword used within loops.

Yes, it is considered a jump statement as it transfers control to the next loop iteration.

A function calling itself to solve smaller instances of a problem.

The process of repeatedly executing a block of code while a condition is met, using constructs like for or while loops.