1

How do you add an item to a specific position on a list. When you have an empty list and want to add 'z' to the 3rd position using insert() only insert it at the last position like,

l.insert(3,'z')
l
['z']

I want the output to be

[None, None, None, 'z']

or

['','','','z']
7
  • 1
    My answer on that question ^ explains why it's not possible (lists aren't sparse), and OP's answer shows something similar to what you want. Commented Aug 15, 2020 at 18:05
  • 1
    For a way to do it automatically: Sparse assignment list in python Commented Aug 15, 2020 at 18:11
  • How is this question the same as the flagged dup link? The answer there is "NO", whereas the question asked here has a minimal reproducible example Commented Aug 15, 2020 at 18:12
  • 1
    the suggested link does not answer my question. Commented Aug 15, 2020 at 18:18
  • 1
    @Akshay Djangonow edited the question right as I was voting to close as duplicate, so I got a bit confused. It's still useful for understanding, but you're right, it doesn't answer the question anymore. Voting to reopen. Commented Aug 15, 2020 at 18:19

2 Answers 2

0

Try this method using a list comprehension -

n = 5
s = 'z'

out = [None if i!=n-1 else s for i in range(n)]
print(out)
[None, None, None, None, 'z']

If you want to insert the string somewhere in the middle, then a more general way is to define m and n separately where n is length of the list and m is the position -

n = 5
m = 3
s = 'z'

out = [None if i!=m-1 else s for i in range(n)]
print(out)
[None, None, 'z', None, None]
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming you want to have it in the Nth index:

l = l[:N] + ['z'] + l[N:]

If you start with an empty list and want it to have Nones at the start and end of array, maybe this will help you (N is the number of None items you want):

l = [None] * N
l = l[:N] + ['z'] + l[N:]

Comments

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.