spen123
spen123

Reputation: 3524

Python - insert into list

I get an array form a csv file and I get an list that looks like

my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']

And now I want to fill the spots where there is '' with an array of items that is that length, lets say the array I want to put in there is

new_array = [1,2,3,4,5,6,7,8]

here is what I am trying but it doesn't work.

i = 0
for item in new_array:
    index = 8+i
    print item
    my_list.insert(index, item)
    i += 0

It doesn't change anything my_list is just the same?

How can I change this?

Thanks

Upvotes: 4

Views: 336

Answers (5)

ashishmohite
ashishmohite

Reputation: 1120

Using list comprehension

>>> new_array = [1,2,3,4,5,6,7,8]
>>> new_array.reverse()
>>> new_array
[8, 7, 6, 5, 4, 3, 2, 1]
>>> [new_array.pop()  if item is '' else item  for item in my_list]
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]

OR

>>> from collections import deque
>>> new_array = deque([1,2,3,4,5,6,7,8])
>>> [new_array.popleft()  if item is '' else item  for item in my_list]
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

This code will work with '' (empty strings) starting at any index:

my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']

starts_at = my_list.index('')
amount_of_empty_strings = 0

for i, item in enumerate(my_list):
    if item.strip() == "":
        my_list[amount_of_empty_strings+starts_at] = amount_of_empty_strings+1
        amount_of_empty_strings+=1

print my_list

Output:

["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

Mikhail Gerasimov
Mikhail Gerasimov

Reputation: 39546

Something like this:

new_iter = iter(new_array)
my_list = [i if i != '' else next(new_iter) for i in my_list]
print(my_list)

Upvotes: 0

Óscar López
Óscar López

Reputation: 236004

Try this:

i = 8
for item in new_array:
    my_list[i] = item # you want to replace the value
    i += 1            # you forgot to increment the variable

You weren't incrementing the variable i, and insert() moves the items to the right, it doesn't substitute them. Of course, a more idiomatic solution would be:

my_list = my_list[:8] + new_array

Upvotes: 3

W. Steve
W. Steve

Reputation: 387

my_list = ["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', '', '', '', '', '', '', '', '']
new_array = [1,2,3,4,5,6,7,8]
i = 0
for item in new_array:
    index = 8+i
    print item
    my_list.remove('')
    my_list.insert(index, item)
    i += 1
print my_list

output:

1
2
3
4
5
6
7
8
["Nov '15", '75', '49', '124', '62', '18', '80', '64.5', 1, 2, 3, 4, 5, 6, 7, 8]

Upvotes: 0

Related Questions