2

In perl I can have what I think are called sparse arrays.

my @a;
$a[4321] = "blah";

and it just does what I want. I don't know how to do this in Python without an error IndexError: list assignment index out of range. What is the (simplest) way to do this in Python?

Lucky
  • 627
  • 5
  • 15
  • In Python, you'd probably want a dictionary - the keys are not required to have any relationship to each other. – jasonharper Oct 29 '22 at 00:23
  • Perl arrays aren't sparse, but as you note they do auto-extend on assignment. You could do [something similar in python](https://stackoverflow.com/questions/4544630/automatically-growing-lists-in-python), but it's not a pythonic thing to do. – craigb Oct 29 '22 at 00:24
  • @jasonharper if I used a dictionary I'd need to sort the keys numerically afterwards. Hmm. – Lucky Oct 29 '22 at 00:40
  • @craigb I'm not a pythonic person, but I can live with being unnecessarily C-ish. I was hoping to avoid exactly that approach though. – Lucky Oct 29 '22 at 00:42
  • That array is not sparse. It has 4322 elements. – ikegami Oct 29 '22 at 01:19
  • @Lucky I think you are looking for this: https://stackoverflow.com/a/8749640/482519 – ernix Nov 01 '22 at 15:26

1 Answers1

1

That array is not sparse. It has 4322 elements.

In Python, the following would create a similar construct:

a = [ None for i in range( 4321 ) ] + [ "blah" ]

If you want to set an element of an array that might be beyond the end of an existing array, @OmnipotentEntity proposed this function.

def set_at( xs, idx, x, default=None ):
   if len( xs ) <= idx:
      xs.extend( [ default ] * ( idx - len( xs ) + 1 ) )
   xs[ idx ] = x

a = [ ]
set_at( a, 4321, "blah" )

If you truly want something sparse, you can use a dictionary with integer keys.

a = { }
a[ 4321 ] = "blah"
ikegami
  • 367,544
  • 15
  • 269
  • 518
  • My Python knowledge is limited. Let me know if there's a better way. – ikegami Oct 29 '22 at 02:14
  • I think that is pythonic, but that would clobber any elements I sprinkled in prior to 4321. In perl I can just do `$a[1234] = "blah"; $a[4321] ="foo"` without wiping the value at 1234. – Lucky Oct 29 '22 at 02:19
  • Re "*but that would clobber any elements I sprinkled in prior to 4321*", I was adding an solution to that as you posted your comment :) See update. – ikegami Oct 29 '22 at 02:24