Home > database >  How will I check and append only if both elements are true in python?
How will I check and append only if both elements are true in python?

Time:01-24

#I want to append the tuple, only if both the elements are two-digit. I have tried to use all function, but ended up with many errors. Please help me to get the desired output

print("The original list is : "   str(test_list))

K = 2
res=[]


for sub in test_list:
    for ele in sub:
        if len(str(ele))==K:
            res.append(sub)
print("The Extracted tuples : "   str(tuple(res)))

#Output that I want enter image description here

#As you can see the output that I want, help to write the proper code for that, Thanks in Advance

CodePudding user response:

You can use the else statement of a for loop. it is useful to check for the condition that is not met:

original_list = [(54, 2), (34,55), (222,23), (12,45), (78,)]
# append tuples if both values have 2 digits
new_list = []
for item in original_list:
    for i in item:
        if len(str(i)) != 2:
            break
    else:
        new_list.append(item)
print(new_list)
#[(34, 55), (12, 45), (78,)]

CodePudding user response:

you probably have some issues with question format, read up on markdown please. Plus, this question is rather specific and doesn't really help others if they read this page, so i think stackoverflow people don't really like this.

Anyways, in your code, you are checking if either of the element is 2 digits, then append. But, the problemt requirement askes you to check both elements of the tuple.

for item1, item2 in test_list: #foreach item in list, grab first and second item
    if len(str(item1)) == 2 and len(str(item2)) == 2: 
        #append to result iff both items have length of 2
        res.append((item1, item2))

CodePudding user response:

You want to include the tuple in the final list if all the elements of the tuple are two-digit; your loop will append the tuple once for each element that is two-digit.

This will do what you're looking for:

print("The original list is :", test_list)
print("The extracted tuples :", [t for t in test_list if all(9 < i < 100 for i in t)])
  •  Tags:  
  • Related