Posts: 9
Threads: 4
Joined: May 2018
So I'm trying to add two lists together with integers in the lists. In both lists there are strings with "null". I want to add the two lists together, but i want the null values of list 1 to be filled with the values that aren't "null" in list 2.
list1 = [5,6,'null',1,'null']
list2 = ['null','null',3,'null',8]
prefered_output = [5,6,3,1,8] I hope you guys can help :)
Posts: 1,150
Threads: 42
Joined: Sep 2016
There are several possible solutions to that. What have you tried so far?
Post your code attempt and we will let you know how to correct it to make it work right.
Posts: 9
Threads: 4
Joined: May 2018
This is what i have tried until now
list1 = [5,6,'null',1,'null']
list2 = ['null','null',3,'null',8]
#prefered_output = [5,6,3,1,8]
prefered_output = []
for n in range(0, len(list1)-1):
if type(list1[n]) != int:
prefered_output[n] = list1[n]
else:
prefered_output[n] = list2[n] However this gives an error: IndexError: list assignment index out of range
Posts: 1,150
Threads: 42
Joined: Sep 2016
Jun-04-2018, 08:26 PM
(This post was last modified: Jun-04-2018, 08:28 PM by j.crater.)
for n in range(0, len(list1)-1) This is not Pythonic, instead it is better to use enumerate():
for index, item in enumerate(list1): On each iteration, "index" will be what you wanted "n" to be, and "item" will be an item from "list1".
You can see how it works with this:
for index, item in enumerate(list1):
print(index, item) And the list assignment error happens because you start with an empty list (prefered_output) and append to an uninitiated index. Instead use list's .append() method.
Posts: 9
Threads: 4
Joined: May 2018
Hey man thank you! i figured it out! This is my code now
list1 = [5,6,'null',1,'null']
list2 = ['null','null',3,'null',8]
#prefered_output = [5,6,3,1,8]
prefered_output = []
for index, item in enumerate(list1):
print(index, item)
if type(list1[index]) != int:
prefered_output.append(list2[index])
else:
prefered_output.append(list1[index])
print(prefered_output) Thanks again :)
Posts: 566
Threads: 10
Joined: Apr 2017
Jun-04-2018, 08:27 PM
(This post was last modified: Jun-04-2018, 08:29 PM by volcano63.)
Why use indexing at all - when you have zip ?
[val2 if val1 == 'null' else val1 for val1, val2 in zip(list1, list2)]
PS Recommended form to check type - isinstance
if isinstance(value, int):
.....
Test everything in a Python shell (iPython, Azure Notebook, etc.) - Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.
|