Everyone!
I am trying to add a new sublist to an existing list, but I am not quite sure on how to do it. Here is my code:
data = [[4,5],[3,7]]
search = 9
for sublist in data:
if search in sublist:
sublist.append(0)
print("there", sublist)
break
else:
print("not there")
break
def sublist():
[5,6]
print[data]
However, if the search is not there, the sublist does not get added to the original list. How can I do this?
Cheers! 5813
Just append it:
>>> data = [[4,5],[3,7]]
>>> data.append([5,6])
>>> data
[[4, 5], [3, 7], [5, 6]]
You should indent your else
block. A for/else is something completely different (although it could work in this case).
If the search isn't in the sublist, then append the sublist (I'm presuming you want to add [5, 6]
to the main list) to data
:
for sublist in data:
if search in sublist:
sublist.append(0)
print("there", sublist)
break
else:
print("not there")
data.append([5, 6])
If you did intent to use a for/else loop, then it's as simple as doing data.append([5, 6])
after the else
. I don't know what you expect the function definition to do (it will do nothing just sitting there).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With