Home > other >  selecting out even number only once without repeating the same number in python list
selecting out even number only once without repeating the same number in python list

Time:05-22

list1 = [2,4,6,8,3,4,2,] From the above list I need to obtain the following result [2,4,6,8]

Here is the way that how I tried. But it resulted an error without giving the expected result.

list1 = [2,4,6,8,3,4,2,]
x=[]
for num in list1:
    if (num % 2 == 0) and (num not in list1):
        x.append(num)
        print(x)

so I need your help to selecting out even numbers only once without repeating the same number Thanks in Advance...!

CodePudding user response:

I've made minor modification to your code, and simply apply set() to get only the unique values, and list() to convert it to a list, and sorted() to get the values in ascending order

list1 = [2,4,6,8,3,4,2,1]
x=[]
for num in list1:
    if (num % 2 == 0):
        x.append(num)
print(sorted(list(set(x))))

Output

[2, 4, 6, 8]

If you need the results to appear in the same order as the original list, you will need to specify the second condition (num not in x), and no need to use set() anymore

list1 = [4,2,8,3,6,5]
x=[]
for num in list1:
    if (num % 2 == 0) and (num not in x):
        x.append(num)

print(sorted(list(set(x))))
print(list(set(x)))
print(set(x))
print(x)

Output

[2, 4, 6, 8]
[8, 2, 4, 6]
{8, 2, 4, 6}
[4, 2, 8, 6]

CodePudding user response:

If you want to go ahead with the same logic, you can update the if condition:

list1 = [2,4,6,8,3,4,2,]
x=[]
for num in list1:
    if (num % 2 == 0) and (num not in x):
        x.append(num)
        print(x)

Other Solution could be using list comprehension and set:

list1 = [2,4,6,8,3,4,2,]
l_set = set(list1)
nums = [val for val in l_set if val%2 == 0]
print(nums)

CodePudding user response:

You can store the number in x as set data type, which prevent duplication, instead of list

list1 = [2,4,6,8,3,4,2]
x=set()
for num in list1:
    if (num % 2 == 0):
      x.add(num)

print(list(x))

Alternatively, if you want to respect the order of the input you can have 1 set and 1 list. The set (x_set) is used for efficient check to see if a number is already in the list and the list (x_output) is used for storing the output

list1 = [2,4,6,8,3,4,2]
x_set=set()
x_output = []
for num in list1:
    if (num % 2 == 0) and (num not in x_set):
      x_set.add(num)
      x_output.append(num)

print(x_output)

CodePudding user response:

With list comprehension, one line is enough. First iterate over the list and test for even. Then convert in set to eliminate duplicates. After return to list:

list({x for x in list1 if x % 2 <= 0})

Output: [8, 2, 4, 6]

  • Related