4

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

1
  • '' always start at index 8? Commented Nov 26, 2015 at 3:26

5 Answers 5

3

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
Sign up to request clarification or add additional context in comments.

Comments

0
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]

Comments

0

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)

Comments

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]

Comments

0

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]

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.