3

I've hit a wall and needed some help or advice to get me through.

I want to append certain strings always apppend to the end of a list.

So we have

List1 = ["sony","cant recall","samsung","dont know","apple","no answer", "toshiba"]

Next we have another list

List2 = ["dont know", "cant recall","no answer"] 

Here is what I've developed so far. The script basically checks if the word in List 1 is in List 2, if found, that particular string should be moved from its current location in the list to the end. But all I can do for now is find the string and its index. I dont know how to move and append the found string to the end of the list.

for p, item in enumerate(list1):
    for i, element in enumerate(list2):
        if item == element:
            print item, p

Thanks!

Charles
  • 50,943
  • 13
  • 104
  • 142
Boosted_d16
  • 13,340
  • 35
  • 98
  • 158

3 Answers3

3

You can do your algorithm like:

 list1 = [x for x in list1 if not x in list2] + [x for x in list1 if x in list2]

which will result in:

['sony', 'samsung', 'apple', 'toshiba', 'cant recall', 'dont know', 'no answer']
Saullo G. P. Castro
  • 56,802
  • 26
  • 179
  • 234
1
lst_result = set(lst1) | set(lst2)

Removes duplicates from the lists as a side effect. Not sure if you want it, but looks like it's assumed.

To keep the ordering:

lst1 = ["sony","cant recall","samsung","dont know","apple", "toshiba"]
lst2 = ["dont know", "cant recall","no answer"]

stripped = list(filter(lambda x: x not in lst2,lst1))
lst_result = stripped + lst2
J0HN
  • 26,063
  • 5
  • 54
  • 85
-1

Here's one way of doing it:

for item in list1:
    if item in list2:
        list1.remove(item)
        list1.append(item)
Lanaru
  • 9,421
  • 7
  • 38
  • 64
  • 4
    Be careful, this won't work if you have two consecutive items from list1 in list 2 (try with list1 = ["sony","cant recall","dont know", "samsung", "apple", "no answer", "toshiba"]) for example. [Directly removing an item from a list while iterating it](http://stackoverflow.com/questions/1207406/remove-items-from-a-list-while-iterating-in-python) is not the best solution. – Pierre Jun 20 '13 at 14:36