Python Arrays

Python Arrays Tutorial

An array is a collection of elements stored in a single variable. In Python, arrays can be implemented using the array module or lists.


1. Difference Between Lists and Arrays in Python

For simple cases, Python lists work as dynamic arrays.
For numerical operations, use array or NumPy for efficiency.


2. Creating an Array in Python

To use an array, import the array module.

import array

# Creating an integer array
arr = array.array('i', [1, 2, 3, 4, 5])

print(arr)  # Output: array('i', [1, 2, 3, 4, 5])

'i' represents an integer array (other types: 'f' for float, 'd' for double, etc.).


3. Accessing Array Elements

print(arr[0])  # Output: 1
print(arr[2])  # Output: 3

Array indexing starts from 0 (like lists).


4. Adding and Removing Elements

Append (Add at the end)

arr.append(6)
print(arr)  # Output: array('i', [1, 2, 3, 4, 5, 6])

Insert (Add at a specific index)

arr.insert(2, 10)  # Insert 10 at index 2
print(arr)  # Output: array('i', [1, 2, 10, 3, 4, 5, 6])

Remove an element

arr.remove(3)  # Removes first occurrence of 3
print(arr)  # Output: array('i', [1, 2, 10, 4, 5, 6])

Pop (Remove by index)

arr.pop(1)  # Removes element at index 1
print(arr)  # Output: array('i', [1, 10, 4, 5, 6])

5. Looping Through an Array

Using a for loop

for num in arr:
    print(num, end=" ")  # Output: 1 10 4 5 6

Using a while loop

i = 0
while i < len(arr):
    print(arr[i], end=" ")
    i += 1
# Output: 1 10 4 5 6

6. Finding the Length of an Array

print(len(arr))  # Output: 5

len() returns the number of elements in the array.


7. Slicing an Array

print(arr[1:4])  # Output: array('i', [10, 4, 5])
print(arr[:3])   # Output: array('i', [1, 10, 4])
print(arr[2:])   # Output: array('i', [4, 5, 6])

Slicing works just like lists.


8. Searching for an Element

print(arr.index(10))  # Output: 1 (Index of element 10)

Returns the first index where the element is found.


9. Sorting an Array

arr = array.array('i', [5, 2, 8, 1, 3])
arr = array.array('i', sorted(arr))

print(arr)  # Output: array('i', [1, 2, 3, 5, 8])

The sorted() function returns a sorted array.


10. Using NumPy for Advanced Arrays

Python’s built-in array module is limited. For more functionality, use NumPy.

Installing NumPy

pip install numpy

Creating a NumPy Array

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr)  # Output: [1 2 3 4 5]

NumPy is optimized for numerical operations and large datasets.


Conclusion

  • Use array for memory-efficient storage of same-type elements.
  • Use lists for flexibility (mixing different types).
  • Use NumPy for powerful numerical operations.

🚀 Let me know if you need more details on a specific part!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment