How to append a new list to an already existing nested list?


#1

my_list = [[‘a’, ‘b’], [‘cc’, ‘dd’, [‘eee’, ‘fff’]], [‘g’, ‘h’]]

# insert a new list [1, 2, 3] at the end of my_list
# Your code goes here
my_list.extend([1, 2, 3])

final_list=[]

for item in my_list:
val=item.split()
final_list.append((val))

print(“Here is the final list:\n”, final_list)

But I get error:
Traceback (most recent call last): File “./prog.py”, line 25, in <module> AttributeError: ‘list’ object has no attribute ‘split’

Can this problem be solved with the knowledge we have attained according to fast track course till this level? We haven’t learnt about split yet on interviewbit and I tried using it while I tried looking on internet around.

Please guide me how do I approach the problem.

I have used extend method to merge the list [1, 2, 3] to my_list. Now how do I convert the items 1, 2, 3 of my_list to a nested list form of my_list?

I was using split to convert list of trailing integers appended to my_list into a single new nested list within my_list. Pointing as my_list[4]


#2

The AttributeError is an exception thrown when an object does not have the attribute you tried to access. The ‘list’ object has no attribute ‘split’ error is that you’re trying to call python split function on the whole list of lines, and you can’t split a list of strings, only a string. So, you need to split each line, not the whole thing.


#3

insert a new list [1, 2, 3] at the end of my_list
instead of using extend use append, and that’s all no need of anything else.

simply use append instead of extend. my_list.append([1, 2, 3])
otherwise my_list.extend([[1, 2, 3]])

As append adds an element to the end of the list, but extend extends the current list to include the elements from the new list. Read the Description above for more details.