0

I am trying to declare a dynamic list in Python and doing various operations with it but after operations it is not giving desired output.

When I declare the list as general length like arr =list() it works fine:

arr = list()
arr.insert(0,5)
arr.insert(1,10)
arr.insert(0,6)
print(arr)
arr.remove(6)
arr.append(9)
arr.append(1)
arr.sort()
print(arr)
arr.pop()
arr.reverse()
print(arr)

This is giving me the expected result:

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

But when I am trying to pass a size to the list it is not giving the expected behavior:

arr = [10]
arr.insert(0,5)
arr.insert(1,10)
arr.insert(0,6)
print(arr)
arr.remove(6)
arr.append(9)
arr.append(1)
arr.sort()
print(arr)
arr.pop()
arr.reverse()
print(arr)

This is giving me:

[6, 5, 10, 10]
[1, 5, 9, 10, 10]
[10, 9, 5, 1]

I am not getting why this is happening.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Mandrek
  • 1,159
  • 6
  • 25
  • 55

1 Answers1

0

arr = [10] doesn't create a list that is ten elements long; it creates a list that contains 1 element, with the value of 10. If you want to create a list that is ten elements long, you could do something like arr = [0 for _ in range(10)].

Izaak Weiss
  • 1,281
  • 9
  • 18