Home > Enterprise >  Appending an array to itself in Python
Appending an array to itself in Python

Time:01-29

I am trying to append an array to itself in python using the inbuilt array module but when I run the code the terminal does not show any output and even does not takes any input it seems like its stuck or something. This is the code I have written.

    arr = array.array("i",[1,2,3,4,5])
    for i in arr:
        arr.append(i)
    print(arr)

When I run the code in the IDLE Shell it shows the error "SyntaxError: invalid syntax"

Why does the code seem to behave unexpectedly?

CodePudding user response:

You're getting an infinite loop because for i in arr: can never reach the end of arr given that you add one more item at every iteration. That's the computer equivalent of a carrot and stick making the donkey move forward yet never reaching the carrot :)

A simpler way to double your array would be to add it to itself with =

arr = array.array("i",[1,2,3,4,5])
arr  = arr

print(arr)
# array('i', [1, 2, 3, 4, 5, 1, 2, 3, 4, 5])

Inserting itself before its first item would also work:

arr[:0] = arr

CodePudding user response:

I think you should create an other array that is a copy of the first one, and you append to the first one the elements of the second one

CodePudding user response:

so, I ran your code in replit. The problem is that you code loops forever, so it never prints anything. The problem is that you are adding onto the list. It's like saying "repeat 3 times," but then each time you repeat, you make it go up (since the list gets larger).The best solution for this is to have two different arrays, and then transfer the values to the other.

arr = ["i",[1,2,3,4,5]]
newArr = []

for i in arr:
    newArr.append(i)
arr = newArr
print(arr)

Also, your code is indented, but not all of it should be. You can select it all press shift tab to move it to the left. Good Luck!

CodePudding user response:

I think you wrote an infinite loop.

This code works on my installation of Python:

from array import array
arr = array("i",[1,2,3,4,5])
arrtwo = array("i",arr)
arrtwo.extend(arr)
print(arrtwo)

A little bit shorter and inplace (it appends arr to arr):

from array import array
arr = array("i",[1,2,3,4,5])
arr.extend(arr)
print(arr)

For information about the array methods, see: https://docs.python.org/3/library/array.html

  •  Tags:  
  • Related