1

I have a full list: f = [A,B,C,D,E].

And short list: s = [A,B,D]

I want to get result list as short list + all rest values from full list that there are not in short list.

Result should be:

nlist = [A,B,D,C,E]

I tried two loops:

let nlist = s
for f in full:
  for s in short:
     if s not in f:
         nlist.append(f)

But I think it is wrong way

Mandalina
  • 87
  • 5

4 Answers4

2

Use list comprehension:

lst = short_lst + [x for x in long_lst if x not in short_lst]
Timur Shtatland
  • 12,024
  • 2
  • 30
  • 47
  • After that operation I got array but elements in short array is in another sequence, I have to safe them – Mandalina May 25 '22 at 17:59
0

If the lists f and s do not contain dublicates (like in your example), it is also possible do the following,

f = ["A", "B", "C", "D", "E"]
s = ["A", "B", "D"]

s.extend(set(f) ^ set(s))
print(s) # output: ['A', 'B', 'D', 'E', 'C']

where the ^ operator is the symmetric difference operator. If you want to know the difference between the difference and symmetric difference, I recommend checking out this question. However, Timur's answer is probably the approach you were looking for.

Soxxes
  • 31
  • 1
  • 1
  • 9
0

Method to concatenate the unique values from multiple lists of different size and sort them:

x = ['I','G','F','A']
y = ['H','E','B','J','B']
z = ['D','C','A']

nlist = sorted(set(x+y+z))
nlist

#output
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J']
Drakax
  • 1,305
  • 3
  • 9
0

For huge full_list size try:

full_list = ['A','B','C','D','E']
short_list = ['A','B','D']

for i,s in enumerate(short_list):
    if s in full_list:
        full_list[full_list.index(s)] = full_list[i]
        full_list[i]=s
print(full_list)

Result

[A,B,D,C,E]

Note

  • This method is slightly faster than others as you sort the full_list inplace.

  • But it's less readable compared to other answers.

Daniel Exxxe
  • 59
  • 1
  • 7