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?

6
  • In Python, you'd probably want a dictionary - the keys are not required to have any relationship to each other. Commented Oct 29, 2022 at 0:23
  • Perl arrays aren't sparse, but as you note they do auto-extend on assignment. You could do something similar in python, but it's not a pythonic thing to do. Commented Oct 29, 2022 at 0:24
  • @jasonharper if I used a dictionary I'd need to sort the keys numerically afterwards. Hmm. Commented Oct 29, 2022 at 0: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. Commented Oct 29, 2022 at 0:42
  • That array is not sparse. It has 4322 elements. Commented Oct 29, 2022 at 1:19

1 Answer 1

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"
Sign up to request clarification or add additional context in comments.

3 Comments

My Python knowledge is limited. Let me know if there's a better way.
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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.