1
How can I insert a value in a non-zero position into an empty list?
Ex:
lista = []
.
.
.
lista.insert(3, 'valor')
1
How can I insert a value in a non-zero position into an empty list?
Ex:
lista = []
.
.
.
lista.insert(3, 'valor')
3
Python lists have the size equal to the number of elements they contain - they are different from "arrays" or "vectors" - although in some texts for beginners they are presented as "vectors".
So there is no way to insert the 3rd element into an empty list - it will always be the first element - why then would the elements be in positions 0 and 1?
Depending on what you want to do, it may be that another data structure might be better for you than a list: you can have a dictionary and use it with numeric keys instead of string for example. And if you always use the "get" method, the unfilled positions in the dictionary work as if they had a default value.
That is, instead of a list
which will have 10 elements, containing "0" by default created with:
dados = [0] * 10
You can create a dictionary, and always access it with get:
dados = {}
...
valor = dados.get(2, 0) # nesse caso, se dados[2] não estiver definido, o get retorna 0.
If you do this, you do not need to create all the elements of the dictionary previously. Already with a list, it will always be necessary.
If the data structure you need is for numerical values, in this case, Python has "array"s of truth - vectors initialized with a number for each position. But except for very specialized problems, the dictionary or lists will be more practical - and if it’s a numerical problem, it’s better to use the numpy library than to use native Python arrays in general. (Python arrays even having "real" positions for the elements, unlike lists, also need to receive explicit initial values - which equals lists for their question)
1
You can write a function capable of filling the empty 'spaces' if the list does not have the proper size using a default value, see only:
def insert_at_pos( lst, pos, val, default=None ):
if( len(lst) > pos ):
lst.insert( pos, val )
else:
for _ in range( pos - len(lst) ):
lst.append( default )
lst.append( val )
return lst
Testing:
l1 = []
l2 = [ 1, 2, 3, 4, 5]
l3 = [ 'foo', 'bar' ]
print( insert_at_pos( l1, 3, 'valor') )
print( insert_at_pos( l2, 3, 'valor') )
print( insert_at_pos( l3, 3, 'valor') )
Exit:
[None, None, None, 'valor']
[1, 2, 3, 'valor', 4, 5]
['foo', 'bar', None, 'valor']
Or, specifying how to fill voids:
l1 = []
l2 = [ 1, 2, 3, 4, 5]
l3 = [ 'foo', 'bar' ]
print( insert_at_pos( l1, 3, 'valor', 'VAZIO' ) )
print( insert_at_pos( l2, 3, 'valor', 'VAZIO' ) )
print( insert_at_pos( l3, 3, 'valor', 'VAZIO' ) )
Exit:
['VAZIO', 'VAZIO', 'VAZIO', 'valor']
[1, 2, 3, 'valor', 4, 5]
['foo', 'bar', 'VAZIO', 'valor']
1
You can use a customized version of List.
import collections
class MyList(collections.UserList):
def insert(self, i, item):
for _ in range(self.__len__(), i):
self.append(None)
super().insert(i, item)
Your code would stand
lista = MyList()
lista.insert(3, 'valor')
print(list)
Resulting in
[None, None, None, 'value']
Browser other questions tagged python list
You are not signed in. Login or sign up in order to post.
Create a non-empty list? What value would be in positions from 0 to 3?
– Woss