0

How can I add an object to a list at a specific spot in Python? This is what I mean:

I want to add the string 'String2' to spot x in a list, but spot x doesn't exist. How can I create spot x?

I want it to be something like this:

list = ['String1']
x = 4
list.create(x)
list[x] = 'String2'
print(list)

Output:

['String1', None, None, 'String2']

4 Answers 4

2

What you're looking for is a sparse list, where values can be entered at arbitrary indices. This question has some possible solutions, like a custom sparse list implementation or using a dict.

Sign up to request clarification or add additional context in comments.

Comments

0

Create your list like this:

initial_size = 4
list = [None] * initial_size
list[0] = 'String1'
list[3] = 'String2'
print(list)           # ['String1', None, None, 'String2']

To increase size of list / add more spaces:

spaces_to_add = 5
list += [None] * spaces_to_add
print(list)           # ['String1', None, None, 'String2', None, None, None, None]

Comments

0

You can do it with something like this, if you really want:

def list_add(list_to_add, data, index):  
if index < len(list_to_add):
    list_to_add[index] = data
else:
    while index > len(list_to_add):
        list_to_add.append(None)
    list_to_add.append(data)

Actually, I don't think that this is the best way to do it, you should use a dictionary with integer indexes like this:

d = {1: 'String1'}
x = 4
d[x] = 'String2'

It is implemented as a hash table, so it has constant lookup times. Read this article, about python dictionaries!

Hope it helps :)

Comments

0

First of all, please, fix your error with indexing.

x = 4

it is not the 4th element, it is the 5th. So you code and result

['String1', None, None, 'String2']

are not compatible.

And you should keep in mind that linked list is not a C-type array stored as one row in memory. You should initialize the range and values, to construct and use it. Consider as a solution:

list = ['String1',None,None,None,None]
x = 4
list[x] = 'String2'
#or (where x - the place where to insert, but not the index!):
#list.insert(x, 'String2')

print(list)

Of course you can automate it generating it with lambda or "*".

Other way - to use arrays or dicts, not lists, and in your case it sounds as right idea, but you are asking for help namely with the list.

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.