Python Program to copy all the elements of an array to another array

In this simple python program, we have to copy the elements of an array to another array. It's an intermediate-level python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is an Array or List?

In this python program example, we use the concept of Arrays in python. An array is a set of elements of the same data type which are stored in sequential memory locations, that can be accessed by an index. Array elements must be the same type. The array is denoted by a[i] where 'a' is the array name and '1' is the subscript to point the element, a[0] will be the first element of the array 'a'.

How to copy elements of an array to another array in python?

In the python language, there are no arrays here we use the list as arrays which is the same as arrays. In this array python program, we are going to copy the elements of one array to another array, to achieve that we have to initialize an array arr1 with some predefined elements in it. Create another array arr2 of the length of the first array. Then we use a for loop in python language to copy each element of the first array arr1[i] to the second array arr2[i]. Finally, we display both arrays.

ALGORITHM

STEP 1: Initialize the first array which we need to copy using the array concept in python language.

STEP 2: Create another array of lengths of the first array using len() method.

STEP 3: Use a for loop starting from zero to the length of the first array.

STEP 4: Assign each value of the first array to the second array in the for loop using arr2[i] = arr1[i];

STEP 5: Use a for loop from zero to the length of the first array and print the elements of the first array using print in the python programming language

STEP 6: Use another for loop from zero tho length of the second array to display the elements in the second copied array using the print statement.

Python Source Code

                                          arr1 = [1, 2, 3, 4, 5];     # define the first array with elements
     
arr2 = [None] * len(arr1);    # create a second array using the len()
     

for i in range(0, len(arr1)):    # Use for loop to assign first array elements to second array
    arr2[i] = arr1[i];     
     

print("Elements of  first array: ");    # display first array
for i in range(0, len(arr1)):    
   print(arr1[i]),    
     
print();    
     
print("Elements of second array: ");    # display the second array
for i in range(0, len(arr2)):    
   print(arr2[i]),  
                                      

OUTPUT

Elements of  first array: 
1
2
3
4
5

Elements of second array: 
1
2
3
4
5