Python Forum

Full Version: Trouble with list function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello and thank you for looking at my post. I am very new to programing and python and am doing exercises from http://www.practicepython.org/solution/2...tions.html . I am on exercise 3. and I have completed the first task however it is asking for me to convert the result of the if statement back into a list. Here is the code I have so far.

a = [1,1,2,3,5,8,13,21,34,55,89]

for element in a:
    if element <= 4:
        print (element)
I need to figure out how to turn the result into a list. I have tried the list function by doing: print list(element) and that threw a syntax error. I have tried it a few other ways all of which have given me syntax errors. I have watched many list tutorials on YouTube and have come here as a last resort. Please forgive me for any errors in my post format and I appreciate all help very much. P.S I am running Python 3
First, the error. print() is only used to display information on the standard out, which is the command line or console. It has no application here.

Now, a skill that will greatly assist you when developing is reading the documentation. It's the best place to begin your research into why something isn't working or what you can do with a particular object. The Python documentation for lists mentions an append() method for lists. Methods are basically functions associated with a particular class. They can be called with dot notation (e.g. list.append()). To implement in your code, you'll want to instantiate a list for your output and loop over list.append() to make it work.

a = [1,1,2,3,5,8,13,21,34,55,89]
out = []
 
for element in a:
    if element <= 4:
        out.append(element)

print(out)
Excellent I am glad I came here. I will refer to documentation and I apologize for my initial error in my posting format. Thank you once again.