-1

Given a list of lists, return a single list, containing all of the elements in the list of lists. The elements of the lists can be of any type.

Sample Run

given_list = [[42,'bottles'], ['of','water','on','the'], ['wall']]
new_list = [42, 'bottles', 'of', 'water', 'on' , 'the', 'wall']

I sort of got my code to work but unlike this sample run I would like the user to enter 2 things for 3 lists and then add those three lists all into one. While keeping those spate lists in the given_list how do I put them all into one big list for new_list?

chepner
  • 497,756
  • 71
  • 530
  • 681
poop
  • 3
  • 1
  • 2
  • 5
  • you can just concatenate lists with `new_List = list1+list2+list3` – R Nar Nov 03 '15 at 21:24
  • WOW thanks! But now another question... If I were to use the code in the sample run: given_list= [ [42,'bottles'] , ['of','water','on','the'] , ['wall']] How would I put all 3 of these lists into one big new_List? – poop Nov 03 '15 at 21:27
  • When i search quickly for 1) combine lists, 2) merge lists i get plenty of answers, why not searching first before asking? – user1767754 Nov 03 '15 at 21:29

3 Answers3

3

You can use extend:

list1 = [42,'bottles']
list2 = ['of','water','on','the']
list3 = ['wall']
new_List = []

new_List.extend(list1)
new_List.extend(list2)
new_List.extend(list3)


print new_List

output: [42, 'bottles', 'of', 'water', 'on', 'the', 'wall']

Ryan
  • 2,058
  • 1
  • 15
  • 29
  • Thanks but if I were to use the sample run with given_list= [ [42,'bottles'] , ['of','water','on','the'] , ['wall']] then how would I turn that all into one new list? – poop Nov 03 '15 at 21:31
  • 1
    @poop given_list being a list of lists, you would just have to loop through that and extend new_list with each inner list. – Andy M Nov 03 '15 at 21:52
  • Yes, use Andy's answer for nested lists. – Ryan Nov 03 '15 at 22:00
2

list(itertools.chain.from_iterable(given_list))?

You could even use sum(given_list, []). Probably not very efficient since it creates lots of intermediary lists.

edit: I should clarify the itertools method is efficient. If you don't want to use a library you could also try [i for inner_list in given_list for i in inner_list].

joechild
  • 111
  • 1
  • 4
2

You need to loop through all of the lists:

for item in list1:
    new_List.append(item)

etc.

Andy M
  • 596
  • 3
  • 7