Saturday, January 4, 2025
HomeQ&APython Arrays

Python Arrays

In Python, arrays are used to store multiple items of the same type in a single variable. They are provided by the array module.

Creating an Array:

python
import array

arr = array.array('i', [1, 2, 3, 4]) # 'i' indicates integer type

Common Operations:

  1. Access Elements:
    python
    print(arr[1]) # Outputs: 2
  2. Add Elements:
    python
    arr.append(5)
  3. Remove Elements:
    python
    arr.remove(2)
  4. Iterate Through an Array:
    python
    for element in arr:
    print(element)

Difference from Lists:

  • Arrays require all elements to be of the same type.
  • Use lists for flexible types and arrays for type-specific collections.
RELATED ARTICLES

Leave a Reply

- Advertisment -

Most Popular

Recent Comments