Skip to content Skip to sidebar Skip to footer

Insert Object To Specific List Index

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 cre

Solution 1:

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.

Solution 2:

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]

Solution 3:

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

deflist_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 :)

Solution 4:

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 = 4list[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.

Post a Comment for "Insert Object To Specific List Index"