Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a New Sublist to an Existing List

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

like image 963
5813 Avatar asked Dec 26 '22 19:12

5813


2 Answers

Just append it:

>>> data = [[4,5],[3,7]]
>>> data.append([5,6])
>>> data
[[4, 5], [3, 7], [5, 6]]
like image 184
dawg Avatar answered Dec 28 '22 09:12

dawg


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).

like image 27
TerryA Avatar answered Dec 28 '22 10:12

TerryA