1

I have two lists with string values, list1 = ['a','g','f','e'] and list2 = [['c','v','d'], ['a','d','e'], ['g','h']]. I want to write a code, that will append list1 into list2 only if first (0th) element in nested list of list2 is not the same as first (0th) element from list1.

This is the code that I wrote, it does not have errors, but It does not do what I want

list1 = ['a','g','f','e']
list2 = [['c','v','d'], ['a','d','e'], ['g','h']]

print('List 1: ', list1)
print('List 2: ', list2)

for nest in list2:
    if list1[0] != nest[0]:
        list2.append(list1)
        print(list2)        
    else:
        print("Not added")
Peter Sutton
  • 1,145
  • 7
  • 20
Void Beats
  • 31
  • 10

2 Answers2

2

You can use the built-in all to check if all first elements of the sublists are not the same as the first element of list1:

if all(l[0] != list1[0] for l in list2):
    list2.append(list1)
slider
  • 12,810
  • 1
  • 26
  • 42
1

Maybe this helps:

list1 = ['a','g','f','e']
list2 = [['c','v','d'], ['a','d','e'], ['g','h']]

print("List 1: ", list1)
print("List 2: ", list2)

for nested_list in list2:
    if nested_list[0] == list1[0]:
        print("Not added")
        break
else:
    list2.append(list1)

print(list2)

The else block after the for loop is executed, if the loop finished without break. You can read more about for-else at Why does python use 'else' after for and while loops? for example.

finefoot
  • 9,914
  • 7
  • 59
  • 102