Search code examples
pythonpython-3.xlistlist-comprehensionslice

Taking all elements except the current element


I want to take all the elements in the list except the current element. Here is the List:

nums = [1, 1, 3, 5, 2, 3, 4, 4]

I tried using list comprehension:

[(nums[:x:],nums[x+1:]) for x in range(len(nums)) ]

This is the output I am getting:

[([], [1, 3, 5, 2, 3, 4, 4]),
 ([1], [3, 5, 2, 3, 4, 4]),
 ([1, 1], [5, 2, 3, 4, 4]),
 ([1, 1, 3], [2, 3, 4, 4]),
 ([1, 1, 3, 5], [3, 4, 4]),
 ([1, 1, 3, 5, 2], [4, 4]),
 ([1, 1, 3, 5, 2, 3], [4]),
 ([1, 1, 3, 5, 2, 3, 4], [])]

I am getting two blank lists one in the beginning and one at the end which is correct. I want to know if there is a way where I can edit these 2 blank lists to [1] by putting any validation?

In essence I need to calculate the product of all the numbers except the current number and I am not allowed to use division.

Also, there is a time constraint that I cannot use nested/multiple for loops as test cases will fail on exceeding time limit


Solution

  • Based on your final goal, it seems like you don't need two separate lists for before/after the current number. Instead, concatenate them and apply prod. That way you don't even need to worry about the empty list issue.

    from math import prod
    
    nums = [1, 1, 3, 5, 2, 3, 4, 4]
    
    prods = [prod(nums[:i] + nums[i+1:]) for i in range(len(nums))]
    print(prods) # [1440, 1440, 480, 288, 720, 480, 360, 360]