2

I want the to directly populate particular sections of a list from a string that is returned by a function. I want to do some binary arithmetic on these elements later. When I access the list using subscript, the elements are not getting stored as I expect. A simplified version of my code is:

   reg_bin_list = ['0']*2
   reg_bin_list[0:1] = "10"

   print reg_bin_list

This puts an extra zero at the end: ['1', '0', '0']

Instead of that if do :

   reg_bin_list = "10"

Then the list is printed correctly as I expect i.e. ['1', '0']

Can anyone help me understand when I access using the index operator, what is going on. Why am I seeing an extra zero at the end?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
peaxol
  • 497
  • 4
  • 13
  • possible duplicate of [How assignment works with python list slice](http://stackoverflow.com/questions/10623302/how-assignment-works-with-python-list-slice) – TigerhawkT3 Jul 23 '15 at 18:54

2 Answers2

4

The problem is with your slicing. [0:1] starts from index 0 and ends before index 1. Hence change the slice to [0:2]

>>> reg_bin_list = ['0']*2
>>> reg_bin_list[0:2] = "10"  # Note the change
>>> reg_bin_list
['1', '0']

Why am I seeing an extra zero at the end?

It is the additional 0 left behind in the original list.

Do have a look at Explain Python's slice notation, for a nice explanation as to why.

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
1

When slicing a list using - list[<start>:<stop>] - the stop index is exclusive, that means it does not get included in the slice.

Hence, when you do -

reg_bin_list[0:1] = "10"

This is only taking the reg_bin_list[0] , and hence it is insert '1' and '0' starting at 0th position, leading to the 3 length list.

You should use -

reg_bin_list[0:2] = "10"

Example -

>>> reg_bin_list[0:2] = "10"
>>> reg_bin_list
['1', '0']
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176