Site icon DataFlair

Python Program on Arrays

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

In this article, we will explore two Python programs that involve the use of arrays, a fundamental data structure in Python. The first program showcases array slicing and different methods of accessing array elements. The second program focuses on dynamically creating an array by taking user input for its elements. Understanding arrays and their manipulation is crucial for efficient data storage and retrieval in Python.

Prerequisites

Topic Explanation

Program 1: Array Slicing and Access

The first program initializes an array, myar, and demonstrates array slicing by printing elements from index 5 to the end. It then shows two methods of accessing array elements: using index numbers with a loop and directly accessing elements using a for loop.

Code:

# Importing the 'array' module and aliasing it as 'arr'
import array as arr

# Creating an integer array 'myar' with initial values
myar = arr.array('i', [100, 20, 10, 40, 30, 50, 55, 22, 44, 99])

# Printing elements from index 5 to the end of the array
print(myar[5:])

# Accessing data using index number
n = len(myar)  # Getting the length of the array
for i in range(n):
    print(myar[i], end=" ")  # Printing each element with a space

# Directly accessing array elements using a for loop
for x in myar:
    print(x, end=" ")  # Printing each element with a space

Output:

array(‘i’, [50, 55, 22, 44, 99])

Code Explanation:

The array module is imported and aliased as ‘arr’

Program 2: Dynamically Creating an Array

The second program dynamically creates an empty array, myar, and takes user input for the limit and elements of the array. It showcases the use of a for loop to populate the array with user input elements.

Code:

# Importing the 'array' module and aliasing it as 'arr'
import array as arr

# Creating an empty integer array 'myar'
myar = arr.array('i', [])

# Taking input for the limit of the array
n = int(input("Enter the limit: "))

# Prompting the user to enter elements in the array
print("Enter elements in the array:")

# Loop to take input from the user and append it to the array
for i in range(n):
    x = int(input())  # Taking input for each element
    myar.append(x)     # Appending the input element to the array

Output:

Enter the limit2
Enter elements in array
4
5

Code Explanation:

1. Takes integer input from the user and stores in x
2. Appends each input element x to myar using myar.append(x)

Summary

In summary, these Python programs offer practical examples of array manipulation. Program 1 demonstrates array slicing and various methods of accessing array elements, while Program 2 showcases the dynamic creation of an array with user-input elements. Understanding arrays is essential for handling collections of data in Python, and these examples contribute to a broader understanding of array operations.

Exit mobile version