0

I have a list of alphabets and want to shift the first few elements to last. This is my list

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

This is my code

alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

shift = int(input("Type the shift number:\n"))
new_alphabet = alphabet
del new_alphabet[0:shift]
new_alphabet+=alphabet[0:shift]
print(new_alphabet)

for example, if the shift is 3, the desired output is:

['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'a', 'b', 'c']

Now, If the shift is again 3 the output that I get from the code is:

['d', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'd', 'e', 'f']

I know the problem is that when I make any change to new_alphabet, simultaneously the same change is made in alphabet leading to such an output. But why is it happening if new_alphabet and alphabet are both different lists?

This doesn't happen when dealing with variables. for example:

a = 2
b = a
b += 1
print(b)
print(a)

Output:

3
2

I am new to python thus, I don't know whether lists can be treated as variables. And also suggest how do I fix this problem.

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
Aarav Jain
  • 21
  • 1
  • 3
  • `alphabet` and `new_alphabet` are the same list. You need to make a copy. – Barmar Nov 17 '21 at 17:24
  • They obviously are **not** different lists. `new_alphabet = alphabet` never creates a copy, ever. Read: https://nedbatchelder.com/text/names.html – juanpa.arrivillaga Nov 17 '21 at 17:25
  • " I don't know whether lists can be treated as variables" what does this mean? "his doesn't happen when dealing with variables" you mean `int` objects? It doesn't happen because *you dont' mutate any int object*. `int` objects are immutable, they do not expose any mutator methods, `list` objects are not, `del new_alphabet[0:shift]` *mutates* the list. If you *had* mutated the `int` object (which is actually technically possible if you are open to using ctypes hijinks) then the behavior would be the same. – juanpa.arrivillaga Nov 17 '21 at 17:26

0 Answers0