How to extract a value from a list if a conditional is met in Python?

Viewed 560

I want to extract the value in a list if a conditional is met. For example in a list [0,0,3,4], I want to extract the value which when added to an index value gives 7, given that the index value of the adding term is higher. So far I can confirm that such a number exists within the list but cannot figure out how to extract the value to use it.

nums=[0,0,3,4]
target=7
for i in range(len(nums)):
    n = target-nums[i] in nums[i+1:]
    print (n)

Output:

False
False
True
False

Since the third output is true, that tells me that (7-3) is in the list at a higher index, but how can I assign the value to a variable rather than the boolean?

3 Answers

This is a common programming question called "two-sum", where given a list nums = [0, 0, 3, 4], and a target target = 7, find two integers in the list which add up to give the target.

There are many ways to solve this online but I'll go based off what you've already written. You know that target-nums[i] in nums[i+1:] is true, so why not assign target-nums[i] to a variable? 7 - 3 == 4

nums=[0,0,3,4]
target=7
for i in range(len(nums)):
    if target-nums[i] in nums[i+1:]:
        n = target-nums[i]
        print(n)

And if you do care about efficiency, then your solution is currently O(n^2) because for each item in the list, you are searching the rest of the list to find its complement. This can be achieved in O(n) complexity (one pass through the list only) using a dictionary.

You can use an expression like this:

n = target-nums[i] if target-nums[i] in nums[i+1:] else None

Or

nums=[0,0,3,4]
target=7
for i in range(len(nums)):
    if target-nums[i] in nums[i+1:]:
        n = target-nums[i]

target-nums[i] in nums[i+1:] returns a Boolean value because we are stating that sth already defined is equal to sth. We can use the Boolean to indicate to python what should be done if True or False:

Here:

nums=[0,0,3,4]
target=7
for i in range(len(nums)):
    if target-nums[i] in nums[i+1:]:
        n = target-nums[i]
        print(n)
Related