Python 3, *args, print the output in a list - python

def even_number(*args):
for even in args:
if even%2==0:
even
print(list(str(even)),end='')
I want to print the output in a list as [8,6,4], but rather it prints it out as [8],[6],[4]. If I put out the last print statement and just print(even), it obviously doesn't list out the output.

Your problem is that you print every time you enter in your if.
Instead, you want to add your number to a list every time you enter the loop and then print it :
def even_number(*args):
my_list = list()
for even in args:
if even%2==0:
my_list.append(even)
print(my_list)
EDIT :
The others answer are correct by the way. It's better to use the comprehension list. I don't remove my answer so you get to understand what your mistake was.

def even_number(*args):
print([i for i in args if i % 2 == 0])

You need to collect the result before printing it if you want to print it as a list, i.e.:
def even_number(*args):
evens = [a for a in args if a % 2 == 0]
print(evens)
# test:
even_number(*range(10)) # [0, 2, 4, 6, 8]

Just use a list comprehension with:
def even_number(*args):
even = [n for n in args if n % 2 == 0]
print(even)

Simple code
def even_number(*args):
result = []
for even in args:
if even % 2 == 0:
result.append(even)
return result
with comprehension list
def even_number(*args):
result = [x for x in args if x%2==0]
return result
for to use function even_number
print even_number(range(10))

Related

*args returns a list containing only those arguments that are even

I'm learning python and in an exercise I need to write a function that takes an arbitrary number of arguments and returns a list containing only those arguments that are even.
My code is wrong I know: (But what is wrong with this code ?)
def myfunc(*args):
for n in args:
if n%2 == 0:
return list(args)
myfunc(1,2,3,4,5,6,7,8,9,10)
Do a list-comprehension which picks elements from args that matches our selection criteria:
def myfunc(*args):
return [n for n in args if n%2 == 0]
print(myfunc(1,2,3,4,5,6,7,8,9,10))
# [2, 4, 6, 8, 10]
This also could be helpful, however, the previous comment looks more advanced:
def myfunc(*args):
lista = []
for i in list(args):
if not i % 2:
lista.append(i)
return lista
Pick evens
def myfunc(*args):
abc = []
for n in args:
if n%2==0:
abc.append(n)
return abc
def myfunc(*args):
mylist = []
for x in list(args):
if x % 2 == 0:
mylist.remove(x)
return mylist
def myfunc(*args):
even=[]
for n in args:
if n %2==0:
even.append(n)
else:
pass
return even
myfunc(1,2,3,4,8,9)
def myfunc(*args):
#solution 1
# Create an empty list
mylist = []
for number in args:
if number %2 == 0:
mylist.append(number)
else:
pass
# return the list
return mylist
#solution 2
# Uses a list comprehension that includes the logic to find all evens and the list comprehension returns a list of those values
# return [n for n in args if n%2 == 0]
You need to create an empty list to contain the even numbers. Also convert your arguments to a list. Then append the even numbers to the newly created list.
def myfunc(*args):
new_list = []
for num in list(args):
if num % 2 == 0:
new_list.append(num)
else:
pass
return new_list
def myfunc(*args):
return [x for x in args if not x&1]
def myfunc(*args):
x=[]
for i in list(args):
if i%2==0:
x.append(i)
return x

CS Circles - Python - Lists - It's Natural exercise

Here is a problem that I am having trouble solving:
Write a function naturalNumbers which takes a positive integer n as input, and returns a list [1, 2, ...] consisting of the first n natural numbers.
Here is the code that I have so far:
def naturalNumbers(x):
x = input()
myList = []
for i in range (0, x):
return myList = myList + [i]
print(myList)
I'm really confused as to when to put return for functions.
you are working very hard
the function range() returns a an object castable to list, so all you need to do is
def naturalNumbers(x):
return list(range(1,x + 1)) #didnt notice we are in python 3
0 is not considered a natural number
Your are mixing both your 'main' code and the function that you are being asked to write.
let your function be only for your list generating function naturalNumbers.
and use a different main function.
you can ignore the main method and the if __name__ = '__main__'
this is just to run correctly with good form.
# this method outputs a list from 0 to x
def naturalNumbers (x):
l = list[]
for i in range(0, x+1):
list.append(i)
return l
def main():
x = input()
# should check if x is an integer (defensive programming)
print (naturalNumbers(x))
if __name__ = "__main__"
main()
also depending on the definition used natural numbers can start form 0 or 1
Return is the output from a function. Without the return the function doesn't 'give back' anything to where it was called.
def naturalNumbers(n):
return [x for x in range(0,n)]
print(naturalNumbers(5))
The above print statement uses the output of natural numbers and will print [0,1,2,3,4].
Say we remove the return and just assign it to a value.
def naturalNumbers(n):
numbers = [x for x in range(0,n)]
#assignment rather than return, we could do other operations.
print(naturalNumbers(5))
#returns None
The above print statement prints 'None' as this is the default return value in Python
def naturalNumbers(n):
n = input()
myList = []
for i in range(1, n + 1):
myList.append(i)
return myList
Or use list comprehension:
def naturalNumbers(n):
n = input()
myList = [i for i in range(1, n + 1)]
return myList
return is the end of a function, it should be outside of a loop.
Try this simple method:
def naturalNumbers(n):
myList = []
for i in range(0,n):
myList = myList+[i+1]
return myList

Print a list of values from these functions

Hello so I was wondering how can I 'print' the list of numbers generated by these functions that take the values from the list and squares them. Thanks!!!
def square(list):
return [i ** 2 for i in list]
def square(list):
return map(lambda x: x ** 2, list)
def square(list):
for i in list:
yield i ** 2
def square(list):
ret = []
for i in list:
ret.append(i ** 2)
return ret
Printing a list by using print, for example:
print(', '.join(map(str, square([5,3,2]))
First off, you need different function names, or else when you call it, python will only take the last one.
To answer your question, it is as easy as using a print statement. Simply print the return of the function while using a list as the argument.
square_list = [1,2,3]
print square(square_list)
If you wanted to try a different way, putting the print statement in the function also works.
For example:
def square(list):
print [i ** 2 for i in list] # Instead of return
The downside of this is you cannot store it as a variable or append it to a list later on.
Happy coding!

Find out the biggest odd number from three arguments in a function [Python]

I need to write a function that will print biggest odd number from three input arguments.
Here is my code.
def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
global odd_number_keeper
if item % 2==1:
odd_number_keeper = [item]
return max(odd_number_keeper)
else:
print 'No odd number is found'
My codes seem is not working. Any ideas how i can modify this code?
A few changes would be needed:
def oddn(x,y,z):
odd_number_keeper = []
for item in [x,y,z]:
if item % 2==1:
odd_number_keeper.append(item)
if not odd_number_keeper:
print 'No odd number is found'
return
return max(odd_number_keeper)
Iterate over the values x, y and z and add the odd numbers to odd_number_keeper. If there are any numbers then you return the max() of the elements in this list of odd numbers. If there are no odd numbers then you print the message and return (without a result, as there is no number to return).
You have to first filter all odd-numbers and then call max:
def oddn(x,y,z):
odd_numbers = [item for item in (x,y,z) if item%2==1]
return max(odd_numbers)
or in short:
def oddn(*numbers):
return max(x for x in numbers if x % 2 == 1)
also it is not good practice, if you want to print some message on error:
def oddn(*numbers):
try:
return max(x for x in numbers if x % 2 == 1)
except ValueError:
print 'No odd number is found'
return None
You are not finding the biggest odd number from the list, instead, you are finding the first odd number and returning that. The issue is in the lines -
odd_number_keeper = [item]
return max(odd_number_keeper)
you first need to be appending item to the list, insteading of making odd_number_keeper the list with only that item.
Secondly, the return statement should be at the end of the function, not inside the for loop.
You need a code something like -
def oddn(x,y,z):
odd_number_keeper = []
for item in x,y,z:
if item % 2==1:
odd_number_keeper.append(item)
return max(odd_number_keeper)
You are resetting odd_number_keeper each time. You probably meant
odd_number_keeper += [item]
Also the return and print should be at the end of (outside) the for loop.
(please fix indentation to be clearer on your intent).
Solving it using filter. Doing it in pythonic way.
def oddn(a, b, c):
final = []
final.append(a)
final.append(b)
final.append(c)
result = filter(lambda x: x % 2 != 0, final)
return max(result)

Repeat a number 3 times for output

I need to define a function which repeats a number 3 times. I can only get it to work as a list where the output is [1, 1, 1] if the input is 1. However I need the output to be 111
This is what I have
def repeat_number(num):
if not type(num) is int:
return None
list_1 = []
x = list_1.append(num)
y = list_1*3
for i in y:
return i,i,i
a = 12
print (repeat_number(a))
and again I want the output to be 121212
def repeat_number3(a):
return str(a)*3
You can use a simple str.join for this, and create a general function:
def repeat(something, times, separator):
return separator.join([str(something) for _ in range(times)])
And now use it to create your specific function:
def repeat_three_times(something):
return repeat(something, 3, '')
Output:
>>> repeat_three_times(1)
'111'
Few things to note:
I've used str to cast the expected integer to a string
I've used a list comprehension to create an iterable which is what str.join expects
I've used str.join to create a string which is a concatenation of the strings in the list (see 2).
Here is an example of using the more general function in a different way:
>>> repeat(1, 4, ',')
'1,1,1,1'
If the output is [1, 1, 1] and you were looking for 111, you can do the following:
print (*repeat_number(a), sep='')
However, I'd recommend doing the following with your function:
def repeat_number(num):
if type(num) != int: return
return int(str(num)*3)
And then all you have to do is:
print (repeat_number(a))
as you originally attempted. Plus, this function returns an actual number, which is probably good.
You can cast the number as a string and multiply.
def repeat(num):
return str(num)*3
a = 12
print(repeat(a))
def repeat_num(x):
return str(x)*3

Categories