Examples of Arrays in Python Programming

0

The array module allows us to store a collection of numeric values.

to use array in python we should put : import array in the beginning of the program array

All Contributions

Slicing Python Arrays :

We can access a range of items in an array by using the slicing operator :

import array as arr
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)
print(numbers_array[2:5]) # 3rd to 5th
print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:])  # 6th to end
print(numbers_array[:])   # beginning to end

We can also concatenate two arrays using + operator

import array as arr
odd = arr.array('i', [1, 3, 5])
even = arr.array('i', [2, 4, 6])
numbers = arr.array('i')   # creating empty array of integer
numbers = odd + even
print(numbers)

We can add one item to the array using the append() method, or add several items using the extend() method :

import array as arr
numbers = arr.array('i', [1, 2, 3])
numbers.append(4)
print(numbers)     # Output: array('i', [1, 2, 3, 4])
# extend() appends iterable to the end of the array
numbers.extend([5, 6, 7])
print(numbers)     # Output: array('i', [1, 2, 3, 4, 5, 6, 7])

Changing and Adding Elements

Arrays are mutable; their elements can be changed in a similar way as lists:

import array as arr
numbers = arr.array('i', [1, 2, 3, 5, 7, 10])
# changing first element
numbers[0] = 0    
print(numbers)     # Output: array('i', [0, 2, 3, 5, 7, 10])
# changing 3rd to 5th element
numbers[2:5] = arr.array('i', [4, 6, 8])   
print(numbers)     # Output: array('i', [0, 2, 4, 6, 8, 10])

Slicing Python Arrays :

We can access a range of items in an array by using the slicing operator :

import array as arr
numbers_list = [2, 5, 62, 5, 42, 52, 48, 5]
numbers_array = arr.array('i', numbers_list)
print(numbers_array[2:5]) # 3rd to 5th
print(numbers_array[:-5]) # beginning to 4th
print(numbers_array[5:])  # 6th to end
print(numbers_array[:])   # beginning to end

total contributions (6)

New to examplegeek.com?

Join us