Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to print an Array
In Python, an array (or list) is a collection of elements stored in a single variable with contiguous memory locations. Each element can be accessed using its index, which starts from 0 for the first element.
Python lists are dynamic and can store homogeneous elements of the same datatype. The index represents the position of each element, ranging from 0 to n-1 for an array with n elements.
Array Indexing
Array indices are the position numbers used to access elements. The first element is at index 0, the second at index 1, and so on. For an array with n elements, the last element is at index n-1.
Steps to Print an Array
Step 1 ? Create an array with elements of the same datatype.
Step 2 ? Use a loop to traverse from index 0 to n-1, where n is the array length.
Step 3 ? Print each element using array[i] notation inside the loop.
Method 1: Using a For Loop
The most common way to print array elements is using a for loop with range ?
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
size = len(arr)
print("The elements present in the array are:")
for i in range(0, size):
print(arr[i])
The elements present in the array are: 1 2 3 4 5 6 7 8 9 10
Method 2: Using Direct Iteration
Python allows direct iteration over list elements without using indices ?
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Array elements using direct iteration:")
for element in arr:
print(element)
Array elements using direct iteration: 1 2 3 4 5 6 7 8 9 10
Method 3: Using join() for Single Line Output
To print all elements in a single line separated by spaces ?
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print("Array elements in single line:")
print(' '.join(map(str, arr)))
Array elements in single line: 1 2 3 4 5 6 7 8 9 10
Comparison
| Method | Use Case | Output Format |
|---|---|---|
| For loop with range | When you need index access | Each element on new line |
| Direct iteration | Simple element printing | Each element on new line |
| join() method | Single line output | Space-separated elements |
Conclusion
Python provides multiple ways to print arrays. Use for loops for indexed access, direct iteration for simplicity, or join() for single-line output. Choose the method that best fits your output requirements.
