Simple list function in Python - python

I am trying to append values (x) to a list if the numbers are divisible by 2 and then print out that list. Seems pretty simple. The following runs but returns None:
x = []
def test():
while x in range(0,100):
if x % 2 == 0:
x.append()
print(test())

Use for to iterate a range - not while.
You have ambiguous meaning to x - both as iteration variable and as a list.
You need to pass the value to append.
You need to return a value so it would be printed through the print statement - otherwise None is the default.
Fixed:
x = []
def test():
for i in range(0,100):
if i % 2 == 0:
x.append(i)
return x
print(test())
Other notes:
You can only use this once. The next call for test would return a list twice the size, since x is a global variable. I believe this is unintended and can be solved by putting the x = [] inside the function.
A list comprehension like [x for x in range(100) if x % 2 == 0] would be much better.

Problems and Fixes
Your have several problems with your code:
You named your list x and your iterate variable x.
You never append a value to your list.
You never return a list from test. Rather than appending to a global list, make a local list in test and return that list.
You're using a while loop when you should be using a for loop.
After the above changes, you code look likes:
def test():
even_numbers = []
for number in range(0, 100):
if number % 2 == 0:
even_numbers.append(number)
return even_numbers
print(test())
Improvements
Note there are better ways to do this. In this case, a list comprehension is a better choice. List comprehensions can be used to avoid the common pattern of building a list of values - such as your case:
def test():
return [n for n in range(0, 100) if n % 2 == 0]
print(test())

Generally you should pass the variable to the function and return it from the function instead of relying on global variables:
def test(x):
...
return x
However while x in range(0, 100) won't work because it will check if x (an empty list) is contained in the range object. But the range only contains numbers so the while loop body will never execute. So you could use a for-loop instead:
def test(x):
for i in range(0, 100):
if i % 2 == 0:
x.append(i)
return x
But you could also use the fact that range supports a step and remove the if by just using step=2:
def test(x):
for i in range(0, 100, 2):
x.append(i)
return x
At this point you could even just extend (append an iterable to) the list:
def test(x):
x.extend(range(0, 100, 2))
return x

You could also use a step of 2 to avoid if tests :
x = []
def test():
for i in range(0,100,2):
x.append(i)
return x
Or use a list comprehension :
x = []
def test():
x = [i for i in range(0,100,2)]
return x
Or use the range it's self as a list:
x = []
def test()
x = list(range(0,100,2))
return x

Rename your inner x variable for simplicity. Use x.append(n) instead of x.append(). Finally, print the variable not the method.

You should either change the list variable or the iteration variable(x in while loop) . and append function works like this list.append(value).

Related

The Function is breaking before providing all values

def list_num_checker(num_list):
for x in num_list:
if x%2==0:
return x
else:
continue
I just began learning Python and this is the code I have written to create a function to return all the even values in a list. However, It breaks down after checking the first even number.E.g.
list_num_checker([1,2,3,4,5,6])
2
Any and all help is appreciated.
return will cause a function to exit... if you use yield you can make it a generator
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x # yield makes this a generator instead
# else: # you don need the else
# continue
for evennum in list_num_checker([1,2,3,4,5,6,7,8]):
print(evennum)
you could also make a list comprehension
print([x for x in num_list if x%2 == 0])
or you could use the builtin filter function
def is_even(num):
return num % 2 == 0
list(filter(is_even,num_list)) # its a generator so you need to call list on it
I think you can use yield instead of return since return will break the for loop and immediately returns the give value
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue
divisible2 = list(list_num_checker([1,2,3,4,5,6]))
Some possible alternative approaches would be to use list comprehension or filter
def list_num_checker(num_list):
return [x for x in num_list if x % 2 == 0]
def list_num_checker(num_list):
return filter(lambda x: x % 2 == 0, num_list)
return will immediately terminate the function. To produce multiple values in one function, use yield instead.
def list_num_checker(num_list):
for x in num_list:
if x%2==0:
yield x
else:
continue

Cannot return the values in the list

I want to return the final value of the list which is new_list[3] but it return nothing at the end. I can get the final value of new_list[3] by using print function. I am quite confusing about the return function. Is it possible it return new_list[times] when the 2 for loop is ended?
original_list = [100,300,400,900,1500]
def filter_list(_list,times):
L = len(_list)
new_list = [list(_list) for k in range(times+1)]
for k in range (0,times):
for j in range (0,L):
if j == 0: #exclude the term [j-1] because new_list[-1] is not exist
new_list[k+1][j] = int(new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
elif j == L-1: #exclude the term [j+1] because new_list[L] is not exist
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2)
else:
new_list[k+1][j] = int(new_list[k][j-1]*0.4 + new_list[k][j]*0.2 + new_list[k][j+1]*0.5)
return (new_list[times])
filter_list(original_list,3)
A function is able to "return" a value back to the scope that called it. If this variable is not stored or passed into another function, it is lost.
For instance:
def f(x):
return x + 1
f(5)
will not print anything since nothing is done with the 6 returned from the f(5) call.
To output the value returned from a function, we can pass it to the print() function:
print(f(5))
or in your case:
print(filter_list(original_list, 3))
This is what the return function does:
A return statement ends the execution of the function call and "returns" the result, i.e. the value of the expression following the return keyword, to the caller. If the return statement is without an expression, the special value None is returned.
You are returning the item but not assigning it to anything
x = filter_list(original_list,3)
print(x)
What this will do is assign whatever you return from your function call to a variable in this case x and then your variable will hold whatever you returned so now
Heres a simple model to visualize this
def something():
x = 1
return x
def something_print():
x = 1
return print(x)
a = something()
print(a)
something_print()
(xenial)vash#localhost:~/python/stack_overflow$ python3.7 fucntion_call.py
1
1

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

for looping and appending into list

list = []
def lecture(x):
for x in range(1,x):
print 'lecture', x
so I have this code that gives the result of
lecture 1
lecture 2
for an input of lecture(3). Now, when I change the code to
list = []
def lecture(x):
for x in range(1,x):
y = 'lecture', x
print y
i get an output of
('lecture', 1)
('lecture', 2)
Ultimately I would like to know why this is the case as I am trying to find a way of appending the first results, the:
lecture 1
lecture 2
into a list but I can't as I get a list with the lecture number separated from its number by a comma etc.
You are getting that strange notation because 'lecture', x is a tuple. A datatype which acts like a list, but a non-flexible list. You can't change them that easily. You have to use the +-operator instead of a comma to put those two values into one variable.
And putting values in a list is done with the append function.
list = []
def lecture(x):
for x in range(1,x):
y = 'lecture' + str(x)
list.append(y);
lecture(5)
Also note:
y = 'lecture' + str(x)
the str(x) is to make sure the different datatypes (int and string) don't conflict. Because String + Int ain't possible.
5 (Int) + 5 (Int) is 10.
5 (String) + 5 (String) is 55.
But 5 (String) + 5 (Int) is an error.
Swap y = 'lecture', x with:
y = 'lecture ' + str(x)
This will append the variable x to 'lecture' and set it in variable y
With the expression y = 'lecture', x, you are creating a tuple. Create an empty list instead, and append values to it with the for loop:
def lecture(x):
lecture_list=[]
for item in range(1,x+1):
y='lecture '+str(item)
lecture_list.append(y)
return lecture_list
An alternative way:
class Lectures(object):
def __init__(self, x):
self.x = x
def __iter__(self):
for i in range(1, self.x):
yield "lecture" + i
Here an iterable class Lectures is made.
First you need to initialize it, passing x as an attribute:
lectures = Lectures(x)
Then you can use it as an iterable:
list_of_lectures = list(lectures)
or
for lecture in lectures:
do_something

Collapse Generator in Python

So I have a function like this:
def demo_range(limit):
value = 0
while value < limit:
yield value
value = value + 1
and this
def demo_generator_to_list(generator):
return [x for x in range(generator)]
Now in the demo_generator_to_list(generator) I need to fill some code to collapse a generator to:
[0,1,2,3]
from
demo_generator_to_list(demo_range(4))
Just pass the generator to a list() call:
def demo_generator_to_list(generator):
return list(generator)
The list() function will iterate over the generator and add all results to a new list object.
You could still use a list comprehension, but then you don't use range():
return [x for x in generator]
This has no advantage over using list(); it is just slower.

Categories