+ 2
List is [1,2,3,4,5,6,7,8....]
If i want to get only 2,4,6,8..... How can I code?
7 Answers
+ 5
HASAN IMTIAZ , Uwltoamym ,
it is not seen as very helpful when we are going to post a ready-made code, as long as the op has *not* shown his attempt here.
it is more helpful to give hints and tips, so that the op has a chance to find a solution by himself.
+ 4
@HASAN's solution is going to produce inaccurate results.
my_list = [1,2,3,4,5]
new_list = [(num * 2) for num in my_list]
That will produce a new_list with all the values doubled. If you want only the even numbers from the list, you need to filter them, not double them.
When what you really want is the even numbers from the list without creating new additional values. For that you should filter it.
That solution is better written like @Uwltoamym suggested. Which is:
nums = [1,2,3,4,5,6,7,8,9,10]
even_nums = [n for n in nums if n % 2 == 0]
There is an alternative to use the filter method on the list, but that is actually less efficient than the solution above. Just to show this, the filter method would be written like this: (( this solution takes more CPU time ))
nums = [1,2,3,4,5,6,7,8,9,10]
even_nums = list(filter(lambda x: x % 2 == 0, nums))
+ 2
Solution is really Simple;
my_list = [1,2,3,4,5]
new_list = [(num * 2) for num in my_list]
print(new_list)
Hope That Will Help you
+ 2
Yet another way: list slicing
nums = [1,2,3,4,5,6,7,8,9]
print(nums[1::2])
Output:
[2, 4, 6, 8]
This slicing syntax [1::2] prints every other element in nums. It starts slicing at index 1 (the second element in nums). The middle part between colons would be the ending index, but because it is not specified it ends at the end of the list. The 2 increments the index by 2 each step:
[ nums[1], nums[3], nums[5], nums[7] ]
If you want the ouput to show only the numbers without list brackets and commas then you may use the extraction operator, *.
print(*nums[1::2])
Output:
2 4 6 8
With commas:
print(*nums[1::2], sep=", ")
Output:
2, 4, 6, 8
+ 1
That is not a great solution
Imagine you have a list in the 1-1000 range.. now youâd have to make a 2nd list with all digits from 1-500.
Use the modulo %
nums = [1,2,3,4,5,6,7,8,9,10]
even_nums = [n for n in nums if n % 2 == 0]
print(even_nums)
+ 1
That's I want
0
Tnx Man