Manipulate Data in Arrays
Introduction
In this article I will show you some examples of how arrays can be manipulated to find certain information using the python programming language.
What is an array
An array is a data structure which is used for storing items of the same data type.
Remove all Occurrences of a Value
# remove value 1 from array
nums = [1, 2, 4, 1, 1, 0, 0, 1, 2, 1]
print(nums)
while 1 in nums:
nums.remove(1)
print(nums)
The code above uses a while loop which creates a if statement saying if 1 is in nums
then loop over the array. After doing this we can repeatedly call the .remove
method and remove the value 1 entirely from the array.
Square the Values and Display in Order
# sqaures elements in array and then displays
# it in decending to ascending order
nums = [-7,-3,2,3,11]
store = []
for i in nums:
square = i ** 2
store.append(square)
print(sorted(store))
The for loop iterates through the array and squares each element . Then the new values are added to an array called store
and they are printed in descending to ascending order using the sorted
method.
Check for Even Numbers in Array
# checks if number of digits is even or odd array
# and then prints out amount of even digit numbers
nums = [12,345,2,6,7896]
count = 0
for i in nums:
if len(str(i)) % 2 == 0:
count += 1
print(count)
The count variable will store the amount of values which are even digits. We loop over the array and convert i
to string to check if the length of the number is even using this % 2 == 0
and if it is even then the number will get added to count
.
Find Maximum Amount of Consecutive Ones
# this will look for the maximum amount of consecutive ones
# and then print the amount
nums = [1,1,0,1,1,1]
count = 0
max_count = 0
for i in nums:
if i == 1:
count += 1
max_count = max(max_count, count)
else:
count = 0
print(max_count)
In order to find the maximum amount of consecutive ones we create two counters called count
and max_count
then we will loop over the nums
array and check if i
is equals to 1 and add it to the count. To then find the maximum number of consecutives we use max_count
and the max
method in python to find the maximum amount and add it to max_count
.