Python Array

 Python array example 


Fast answer

In Python, an array-like structure is most commonly a list.


Example using a list

# Create an array (list)

numbers = [10, 20, 30, 40, 50]


# Access elements

print(numbers[0])   # 10

print(numbers[2])   # 30


# Modify an element

numbers[1] = 25


# Add an element

numbers.append(60)


# Loop through the array

for num in numbers:

    print(num)


print(numbers)

Output:


10

30

10

25

30

40

50

60

[10, 25, 30, 40, 50, 60]

Example using the array module

If you need an actual typed array (all elements of the same type), use the built-in array module:


from array import array


# Create an integer array

numbers = array('i', [10, 20, 30, 40])


print(numbers[0])   # 10


numbers.append(50)


for num in numbers:

    print(num)

Here, 'i' means the array stores integers.


For most Python programs, lists are the preferred and most commonly used choice. The array module is useful when you specifically need a more memory-efficient collection of a single data type.



No file chosen

Comments