-1

Im having 2 lists. Looping list2 and checking if list1 elements exists in list2 or not.But my below code is checking for only exact match and not considering upper case or lower case elements like Date, CIRCUIT

list1 = ['circuit', 'Date', 'common', 'discover']
list2 = [('id-23', 'po'), ('id-24', 'date'),('id-25', 'CIRCUIT'), ('id-26', 'discover')]

for i, a in list2:
    if a in list1:
        kia = i,a
        print(kia)

Output im getting is ('id-26', 'discover')

expected output should be ('id-24', 'date'), ('id-25', 'CIRCUIT'), ('id-26', 'discover')

rdas
  • 20,604
  • 6
  • 33
  • 46
harsha kazama
  • 159
  • 2
  • 4
  • 18
  • 1
    please check https://stackoverflow.com/questions/319426/how-do-i-do-a-case-insensitive-string-comparison – zedv May 17 '20 at 14:29

5 Answers5

1

You can convert to lower and check the values

list1 = ['circuit', 'Date', 'common', 'discover']
list2 = [('id-23', 'po'), ('id-24', 'date'),('id-25', 'CIRCUIT'), ('id-26', 'discover')]
list1 = [i.lower() for i in list1]

for i, a in list2:
    if a.lower() in list1:
        kia = i,a
        print(kia)
1

Case insensitivity can be achieved by converting all elements to either all upper case or all lower case. For example:

for i, a in list2:
    if a.lower() in [x.lower() for x in list1]:

This ignores case within both list 1 and list 2 and uses list comprehension to create a list of all lower case elements. This could also be achieved using the map function as such:

map(str.lower, list1)

As noted by @Asocia, this can be inefficient so it would be better to move the list comprehension outside the for loop as such:

lowerList = [x.lower() for x in list1]
for i, a in list2:
    if a.lower() in lowerList:
sebjose
  • 36
  • 3
0

Turn list1 into lowercase and then search for the lowercased a in that list

list1 = ['circuit', 'Date', 'common', 'discover']
list2 = [('id-23', 'po'), ('id-24', 'date'),('id-25', 'CIRCUIT'), ('id-26', 'discover')]

list1_lower = [item.lower() for item in list1]  # turn everything to lowercase

for i, a in list2:
    if a.lower() in list1_lower:  # search if lowercased a is in list1
        kia = i,a
        print(kia)
rdas
  • 20,604
  • 6
  • 33
  • 46
0

You can 1) convert all strings in list1 to all lower cases, and 2) convert a to lower case too inside the loop:

list1_ = [x.lower() for x in list1]
for i, a in list2:
    if a.lower() in list1_:
    kia = i,a
    print(kia)
xcmkz
  • 677
  • 4
  • 15
0

You can use upper() for the selection process.

list1 = ['circuit', 'Date', 'common', 'discover']
list2 = [('id-23', 'po'), ('id-24', 'date'),('id-25', 'CIRCUIT'), ('id-26', 'discover')]

list3 = [(id,el) for id,el in list2 if el.upper() in map(str.upper, list1)]

print(list3)
LevB
  • 925
  • 6
  • 10