0
array='abcdcba'
array=list(array)
palindrome=[]

for x in range (0,len(array)):
    list1 = []
    list1.append(array[x])
    for y in range(x+1,len(array)):
        list1.append(array[y])
        list2=list1[::-1]
        if list1==list2:
            palindrome.append(list1)
print(palindrome)

I'm trying to find the palindromes in the given string, and I'm experiencing weird behaviour.

When I find the palindrome bcdcb, I append the list to the palindrome array. Then when I append a new value to list1 in the next iteration, the value gets appended to the palindrome list too; making it bcdcba

The same happens to cdc; it prints it as cdcba.

The output I'm getting is:

[['a', 'b', 'c', 'd', 'c', 'b', 'a'], ['b', 'c', 'd', 'c', 'b', 'a'], ['c', 'd', 'c', 'b', 'a']]
zondo
  • 19,901
  • 8
  • 44
  • 83
Grigor Carran
  • 89
  • 1
  • 8
  • The `for y in...` loop keeps using the same `list1` on every iteration. Did you mean to put `list1 = []` into that inner loop rather than the outer one? – TigerhawkT3 Apr 05 '17 at 02:08

2 Answers2

1

A usual problem: you have only one list list1 object (until you re-initialize it with list1 = []). To make sure you don't modify the palindromes you've found, just make a copy of list1 first before you append it, this way when you later modify list1 that copy won't change:

array='abcdcba'
array=list(array)
palindrome=[]

for x in range (0,len(array)):
    list1 = []
    list1.append(array[x])
    for y in range(x+1,len(array)):
        list1.append(array[y])
        list2=list1[::-1]
        if list1==list2:
            palindrome.append(list1[:]) # copy list1
print(palindrome)
Julien
  • 13,986
  • 5
  • 29
  • 53
-1

Here's how I was able to achieve this:

w = input("Type in a word. ")
wL = []
for y in w:
    wL.append(y)
print(wL)
if (wL[::] == wL[::-1]:
    print("This is a palindrome")
else:
    print("This is not a palindrome")
skwidbreth
  • 7,888
  • 11
  • 58
  • 105
Fronin
  • 27
  • 5