Print a list of values from these functions - python

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!

Related

To return elements of a list from a function

I want to define a function that takes a list as its argument and then returns the elements in order.
For example:
def iterator(lis):
for e in range(len(lis)):
return lis[e]
l=input("Enter list elements:").split()
x=iterator(l)
print(x)
But this just returns the first value of the list as:
Enter list elements:12 23 34
12
How can I print all the values in successive lines?
You can use yield in order to build a generator, here's the official documentation about Generators
What is a generator in Python?
A Python generator is a function which returns a generator iterator
(just an object we can iterate over) by calling yield. yield may be
called with a value, in which case that value is treated as the
"generated" value.
I also want to share an example, be sure to read the comments:
def iterator(lis):
for e in range(len(lis)):
yield lis[e]
l=input("Enter list elements:").split()
# A generator returns an Iterable so you should
# loop to print
for number in iterator(l):
print(number)
# Or use list
result = list(iterator(l))
print(result)
Output
1
2
3
['1', '2', '3']
You probably want yield, as return causes the function call to end immediately. But yield just produces another iterator; you still need to iterate over the result to print them all, rather than simply printing the iterator itself.
def iterator(lis):
for e in range(len(lis)):
yield lis[e]
...
for element in x:
print(element)
Of course, you are pretty much just reimplementing the existing list iterator here; an equivalent definition would be
def iterator(lis):
yield from lis
What you might want instead is to do something like
x = '\n'.join(l)
print(x)
which creates a string by iterating over l and joining the elements using \n. The resulting multiline string can then be printed.
It will print only one element if you do return
def iterator(lis):
for e in range(len(lis)):
return lis[e]
l=input("Enter list elements:").split()
x=iterator(l)
for y in x: print(y)
Use:
def iterator(list):
for e in range(len(list)):
a= list[e]
print(a)
l=a,b,c=input().split()
a=iterator(l)
Use:
[print(i) for i in input("Enter list elements:").split(" ")]
return causes the function to stop after it hits the statement. So your for loop only ever runs once.
You could use yield as mentioned in the other answers, but I really don't think you need a function in this situation. Because the function is just going to return the list that it took as an argument. What you should do is something like this:
i = input("Enter list elements: ").split()
for x in i:
print(x)
It's that simple.
def iterator(lis):
for e in range(len(lis)):
print( lis[e])
l=input("Enter list elements:").split()
iterator(l)
if you want to do some operations for each item in the list, then you should accomodate those within the function.
Use of print instead of return will give you the expected output..try it once

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

Using simple Recursion to create a list

I want every element in l(which is a list) to be added to a.
When I run the function, it gives me '[]' every time. How can I fix this?
def sim(l):
a = []
if len(l)>0:
a = a.append(l.pop())
l.pop()
return sim(l)
return a
Several things are wrong:
You shouldn't use lowercase L for a variable name - it looks like one
At the top of the function you assign an empty list to a - ultimately sim will be called with an empty list, then a will be assigned an empty list, the conditional statement will fail and sim will return an empty list.
Inside the conditional statement you assign the return value of list.append() to a. The return value is None so whatever a was before, it gets wiped out.
Inside the conditional statement you pop() two items out of your control list
An empty list has a boolean value of false so there is no need to explicitly check its length,
def sim(el, a = None):
if el:
a.append(el.pop())
return sim(el, a)
return a
I was taught to write the base case of a recursive function as the first statement:
def sim(el, a = None):
if not el:
return a
a.append(el.pop())
return sim(el, a)
append() doesn't return anything but does update the existing list. In other words, by trying to assign the result of the append() method, you're setting a to nothing after you have already appended the item.
Your Code :def sim(l):
a = []
when you call Function recursively return sim(l) every time it is call sim(l) and a=[] is empty.
Try This :
def sim(l,a):
if len(l)>0:
a.append(l.pop())
print a
return sim(l,a)
return a
Is this a homework assignment where you're required to do it in a certain (overly complicated) way? Because if not, you can add one list to another in Python like so:
>>> l = [1, 2, 3]
>>> a = []
>>> a.extend(l)
>>> a
[1, 2, 3]

Why does list.append() return None? [duplicate]

This question already has answers here:
Why do these list operations (methods: clear / extend / reverse / append / sort / remove) return None, rather than the resulting list?
(6 answers)
Closed 2 years ago.
I am trying to calculate a postfix expression using Python, but it did not work. I think this is maybe a Python-related problem.
Any suggestions?
expression = [12, 23, 3, '*', '+', 4, '-', 86, 2, '/', '+']
def add(a,b):
return a + b
def multi(a,b):
return a* b
def sub(a,b):
return a - b
def div(a,b):
return a/ b
def calc(opt,x,y):
calculation = {'+':lambda:add(x,y),
'*':lambda:multi(x,y),
'-':lambda:sub(x,y),
'/':lambda:div(x,y)}
return calculation[opt]()
def eval_postfix(expression):
a_list = []
for one in expression:
if type(one)==int:
a_list.append(one)
else:
y=a_list.pop()
x= a_list.pop()
r = calc(one,x,y)
a_list = a_list.append(r)
return content
print eval_postfix(expression)
Just replace a_list = a_list.append(r) with a_list.append(r).
Most functions, methods that change the items of sequence/mapping does return None: list.sort, list.append, dict.clear ...
Not directly related, but see Why doesn’t list.sort() return the sorted list?.
The method append does not return anything:
>>> l=[]
>>> print l.append(2)
None
You must not write:
l = l.append(2)
But simply:
l.append(2)
In your example, replace:
a_list = a_list.append(r)
to
a_list.append(r)
For return data on append use:
b = []
a = b.__add__(['your_data_here'])
append function mutates the list and it returns None. This is the piece of code which does that http://hg.python.org/cpython/file/aa3a7d5e0478/Objects/listobject.c#l791
listappend(PyListObject *self, PyObject *v)
{
if (app1(self, v) == 0)
Py_RETURN_NONE;
return NULL;
}
So, when you say
a_list = a_list.append(r)
you are actually assigning a_list with None. So, the next time when you refer to a_list, it is not pointing to the list but the None. So, as others have suggested, change
a_list = a_list.append(r)
to
a_list.append(r)
Functions like list.append(),list.sort() don't return anything.
e.g
def list_append(p):
p+=[4]
function list_append doesn't have an return statement.so when you run following statements:
a=[1,2,3]
a=list_append(a)
print a
>>>None
but when you run following statements:
a=[1,2,3]
list_append(a)
print a
>>>[1,2,3,4]
That's it.so,hoping it can help you.
List methods can be divided in two types those who mutate the lists in place and return None (literally) and those who leave lists intact and return some value related to the list.
First category:
append
extend
insert
remove
sort
reverse
Second category:
count
index
The following example explains the differences.
lstb=list('Albert')
lstc=list('Einstein')
lstd=lstb+lstc
lstb.extend(lstc)
# Now lstd and lstb are same
print(lstd)
print(lstb)
lstd.insert(6,'|')
# These list-methods modify the lists in place. But the returned
# value is None if successful except for methods like count, pop.
print(lstd)
lstd.remove('|')
print(lstd)
# The following return the None value
lstf=lstd.insert(6,'|')
# Here lstf is not a list.
# Such assignment is incorrect in practice.
# Instead use lstd itself which is what you want.
print(lstf)
lstb.reverse()
print(lstb)
lstb.sort()
print(lstb)
c=lstb.count('n')
print(c)
i=lstb.index('r')
print(i)
pop method does both. It mutates the list as well as return a value.
popped_up=lstc.pop()
print(popped_up)
print(lstc)
just a thought, instead of those functions (which manipulates the actual data) returning None, they should have returned nothing.
Then atleast the user would have caught the issue as it would have throwed an error stating some assignment error!!
Comment your thoughts!!
Just in case somebody ends here, I encountered this behavior while trying to append on a return call
This works as expected
def fun():
li = list(np.random.randint(0,101,4))
li.append("string")
return li
This returns None
def fun():
li = list(np.random.randint(0,101,4))
return li.append("string")

(Python 2.7) Use a list as an argument in a function?

So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x): doesn't work either though. What am I supposed to do here?
Edit: Thanks for the help everyone, I see what I was doing wrong now.
There are a handful of problems here:
You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
You're using your argument, x, as the placeholder for items in your list when you iterate over it, which means after the loop, x no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x afterward, but for clarity it's better to use a different variable name.
Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list has a count() method, as does tuple, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!
when you pass *x to a function, then x is a list. Do either
def function(x):
# x is a variable
...
function('foo') # pass a single variable
funciton(['foo', 'bar']) # pass a list, explicitly
or
def function(*args):
# args is a list of unspecified size
...
function('foo') # x is list of 1 element
function('foo', 'bar') # x is list with two elements
Your function isn't taking a list as an argument. *x expands to consume your passed arguments, so your function is expecting to be called like this:
f(1, 2, 3)
Not like this:
f([1, 2, 3])
Notice the lack of a list object in your first example. Get rid of the *, as you don't need it:
# Write your function below!
def fizz_count(lst):
count = 0
for elem in lst:
if elem == "fizz":
count += 1
return count
You can also just use list.count:
# Write your function below!
def fizz_count(lst):
return lst.count('fizz')
It must be a typo. You're trying to iterate over the function name.
try this:
def fizz_count(x):
counter = 0
for element in x:
if element == "fizz":
counter += 1
return counter
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for i in x:
if i == "fizz":
count += 1
return count
Sample :
>>> fizz_count(['test','fizz','buzz'])
1
for i in x: will iterate through every elements of list x. Suggest you to read more here.

Categories