Python printing list element - python

I noticed that in the following snippet both approaches give the same result:
>>> a = [1,2,3]
>>> print(a[0])
1
>>> print(a)[0]
1
>>>
I was a bit surprised, as I would have expected print(a) to return a string, so then subscript 0 to just return the first character (Ie: [). However, it seems Python interprets it as a list?
Anybody able to clarify please?

As mentioned, you're using python 2.x, where print is a statement, not a function — so print(a)[0] being parsed as print a[0] — treating braces as parsing priority modifier.
Important thing — print does not return what you're printing. It sends data to stream (stdout by default). If you're using python 3.x (where print is a function) or use from __future__ import print_function — functions will send data to stream and return None as result. So print(a)[0] will resolve to "send content of a to stdout and return None[0]", later will raise IndexError

As #jonrsharpe mentioned in the comment block, you're probably running python 2.x.
print statement was replaced in python 3.x with print() function
>>> print(a)[0]
[1, 2, 3]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not subscriptable

Related

Why is print("{}").format() valid syntax?

Ran into some interesting Python behavior today. I though I was writing
print("{}".format("some value"))
but instead I wrote
print("{}").format("some value")
and funnily enough it worked. So my question is, how does this work?
Digging deeper
This behavior seems to be python2 specific.
Python2.7
>>> print("{}").format("testing")
testing
Python3.4
>>> print("{}").format("testing)
File "<stdin>", line 1
print("{}").format("testing)
^
SyntaxError: EOL while scanning string literal
It also seems like the print function of python2 doesn't have a return value but Python3 does? so that confuses me even more.
Python2.7
>>> type(print("testing))
File "<stdin>", line 1
type(print("testing))
^
SyntaxError: invalid syntax
>>> a = print("testing")
File "<stdin>", line 1
a = print("testing")
^
SyntaxError: invalid syntax
Python3.4
>>> type(print("{}"))
{}
<class 'NoneType'>
>>> a = print("{}")
{}
>>> a
>>> type(a)
<class 'NoneType'>
In Python 2, print is a statement, not a function (unless you do from __future__ import print_function at the top of your module). This means that the parentheses around the thing you're printing are not part of a function call, but just treated as grouping parentheses. In the situation you describe ("{}") is the same as "{}" (the parens do nothing), so the format call works just like you'd expect if you wrote "{}".format(...).
In Python 3, print is a function, so the parentheses are not optional and can't be put in the wrong place. print returns None, so you're almost certainly going to get an error if you do print(something).something_else, since None doesn't have a something_else attribute.
In Python 2.7, print is a statement; this means that
print("{}").format("testing")
prints one expression, the result of the expression ("{}").format("testing"). That is, the format method is called on the (parenthesized) string before the print statement is evaluated. If you use
from __future__ import print_function
in the 2.7 examples, you'll get identical behavior to Python 3.
You're missing the closing quote after some strings (e.g. "testing).
As others are saying, Python 2 doesn't have a print() function, it has a print statement. Your strings (even if they were properly closed) are not what and where you think they are.
In Python 2, print is a statement keyword like raise, not a function. Parentheses aren't used for its arguments, and so print("{}").format("testing") is parsed as though you'd written print ("{}").format("testing"), which is the same as print(("{}").format("testing")). Because print is a statement, it cannot be used as an expression, and therefore it cannot have a return value.
If you want print in Python 2 to act like Python 3's print function, place this line at the top of your file:
from __future__ import print_function

Why does "example = list(...)" result in "TypeError: 'list' object is not callable"? [duplicate]

This question already has answers here:
Why does code like `str = str(...)` cause a TypeError, but only the second time?
(20 answers)
Closed last month.
I tried to use this code from a tutorial at the REPL:
example = list('easyhoss')
The tutorial says that example should become equal to a list ['e', 'a', 's', 'y', 'h', 'o', 's', 's']. But I got an error instead:
>>> example = list('easyhoss')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
Why did this happen?
Seems like you've shadowed the builtin name list, which points at a class, by the same name pointing at an instance of it. Here is an example:
>>> example = list('easyhoss') # here `list` refers to the builtin class
>>> list = list('abc') # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss') # here `list` refers to the instance
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: 'list' object is not callable
I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:
Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest them. As I've already mentioned, they are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace, though in fact it's just a local namespace with respect to that particular module.
Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.
Here is a simple illustration.
>>> example = list("abc") # Works fine
>>>
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>>
>>> example = list("abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>>
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name.
>>> example = list("abc") # It works.
So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.
You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).
If you want to know more about builtins, please read the answer by Christian Dean.
P.S. When you start an interactive Python session, you create a temporary module.
Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.
What is a built-in name?
In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.
As of the latest version of Python - 3.6.2 - there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.
An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.
Here is an example using the dict built-in:
>>> dict = {}
>>> dict
{}
>>>
As you can see, Python allowed us to assign the dict name, to reference a dictionary object.
What does "TypeError: 'list' object is not callable" mean?
To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:
list = [1, 2, 3, 4, 5]
When you did this, you overwrote the predefined value of the built-in name. This means you can no longer use the predefined value of list, which is a class object representing Python list.
Thus, when you tried to use the list class to create a new list from a range object:
myrange = list(range(1, 10))
Python raised an error. The reason the error says "'list' object is not callable", is because as said above, the name list was referring to a list object. So the above would be the equivalent of doing:
[1, 2, 3, 4, 5](range(1, 10))
Which of course makes no sense. You cannot call a list object.
How can I fix the error?
Suppose you have code such as the following:
list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))
for number in list:
if number in myrange:
print(number, 'is between 1 and 10')
Running the above code produces the following error:
Traceback (most recent call last):
File "python", line 2, in <module>
TypeError: 'list' object is not callable
If you are getting a similar error such as the one above saying an "object is not callable", chances are you used a builtin name as a variable in your code. In this case and other cases the fix is as simple as renaming the offending variable. For example, to fix the above code, we could rename our list variable to ints:
ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))
for number in ints: # Renamed "list" to "ints"
if number in myrange:
print(number, 'is between 1 and 10')
PEP8 - the official Python style guide - includes many recommendations on naming variables.
This is a very common error new and old Python users make. This is why it's important to always avoid using built-in names as variables such as str, dict, list, range, etc.
Many linters and IDEs will warn you when you attempt to use a built-in name as a variable. If your frequently make this mistake, it may be worth your time to invest in one of these programs.
I didn't rename a built-in name, but I'm still getting "TypeError: 'list' object is not callable". What gives?
Another common cause for the above error is attempting to index a list using parenthesis (()) rather than square brackets ([]). For example:
>>> lst = [1, 2]
>>> lst(0)
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
lst(0)
TypeError: 'list' object is not callable
For an explanation of the full problem and what can be done to fix it, see TypeError: 'list' object is not callable while trying to access a list.
If you are in a interactive session and don't want to restart you can remove the shadowing with
del list
In the league of stupid Monday morning mistakes, using round brackets instead of square brackets when trying to access an item in the list will also give you the same error message:
l=[1,2,3]
print(l[2])#GOOD
print(l(2))#BAD
TypeError: 'list' object is not callable
You may have used built-in name 'list' for a variable in your code.
If you are using Jupyter notebook, sometimes even if you change the name of that variable from 'list' to something different and rerun that cell, you may still get the error. In this case you need to restart the Kernal.
In order to make sure that the name has change, click on the word 'list' when you are creating a list object and press Shift+Tab, and check if Docstring shows it as an empty list.
Why does TypeError: 'list' object is not callable appear?
Explanation:
It is because you defined list as a variable before (i am pretty sure), so it would be a list, not the function anymore, that's why everyone shouldn't name variables functions, the below is the same as what you're doing now:
>>> [1,2,3]()
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
[1,2,3]()
TypeError: 'list' object is not callable
>>>
So you need it to be the default function of list, how to detect if it is? just use:
>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
list()
TypeError: 'list' object is not callable
>>>
How do i detect whether a variable name is a function? well, just simple see if it has a different color, or use a code like:
>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>>
After this, you should know why does TypeError: 'list' object is not callable appear.
Okay, so now...
How to fix this TypeError: 'list' object is not callable error?
Code:
You have to either do __builtins__.list():
>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>>
Or use []:
>>> list = [1,2,3]
>>> []
[]
>>>
Or remove list variable from memory:
>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>>
Or just rename the variable:
>>> lst = [1,2,3]
>>> list()
[]
>>>
P.S. Last one is the most preferable i guess :-)
There are a whole bunch of solutions that work.
References:
'id' is a bad variable name in Python
How do I use a keyword as a variable name?
How to use reserved keyword as the name of variable in python?
find out what you have assigned to 'list' by displaying it
>>> print(list)
if it has content, you have to clean it with
>>> del list
now display 'list' again and expect this
<class 'list'>
Once you see this, you can proceed with your copy.
For me it was a flask server returning some videos array (which I expected to be in json format..)
adding json.dumps(videos) fixed this issue
I was getting this error for another reason:
I accidentally had a blank list created in my __init__ which had the same name as a method I was trying to call (I had just finished refactoring a bit and the variable was no longer needed, but I missed it when cleaning up). So when I was instantiating the class and trying to call the method, it thought I was referencing the list object, not the method:
class DumbMistake:
def __init__(self, k, v):
self.k = k
self.v = v
self.update = []
def update(self):
// do updates to k, v, etc
if __name__ == '__main__':
DumbMistake().update('one,two,three', '1,2,3')
So it was trying to assign the two strings to self.update[] instead of calling the update() method. Removed the variable and it all worked as intended. Hope this helps someone.
You have already assigned a value to list.
So, you cannot use the list() when it’s a variable.
Restart the shell or IDE, by pressing Ctrl+F6 on your computer.
Hope this works too.
I found myself getting this error because I had a method that returned a list that I gave a #property decorator. I forgot about the decorator and was calling method() instead of just method which gave this same error.
Why error occurred?
Because you have named any of your list as "list" in current kernel.
example:
import operator
list = [1, 4, 5, 7, 9, 11]
#you are naming list as "list"
print("The sum is : ", end="")
print(list(itertools.accumulate(list1)))
print("The product is : ", end="")
print(list(itertools.accumulate(list1, operator.mul)))
Solution:
Simply restart the kernel.
Close the current interpreter using exit() command and reopen typing python to start your work. And do not name a list as list literally. Then you will be fine.
to solve the error like this one: "list object is not callable in python" even you are changing the variable name then please restart the kernel in Python Jutyter Notebook if you are using it or simply restart the IDE.
I hope this will work. Thank you!!!

AttributeError: 'NoneType' object has no attribute 'format'

print ("Hello World")
print ("{} World").format(Hello)
I'm working on my first "Hello World" program and I can get it to work by using the print function and just a simple string text but when I try to use .format it gives me the error:
AttributeError: 'NoneType' object has no attribute 'format'
Is this saying that I need to initialize a variable for .format or am I missing something?
Your brackets are wrong
print("Hello World")
print("{} World".format('Hello'))
Note - the errors
The format function is an attribute of str so it needs to be called on the string
Unless declared, Hello is a string and should be 'Hello'
For Py2 you can do
print "{} World".format('Hello')
Function print returns None, so that's obviously what you're getting from the start of your second statement, namely
print ("{} World")
On that return value of None, you then call .format(Hello) -- even if a variable named Hello was assigned somewhere in your code (and you're not showing it to us!), you're calling that .format method on the None returned from your print call, which makes no sense.
Rather, you want to call .format on the string "{} World" -- so the closed-paren right after the string and before the dot is clearly a terrible mistake! Move that ) to the end of the statement, after the call to format on that string.
Moreover, is Hello the name of a variable whose value you want to format? I sure hope not, else why haven't you shown us that variable being assigned?! I suspect you want to format a constant string and just absent-mindedly forgot to put it in quotes (to show it's a constant, not the name of a variable!) -- 'Hello', not Hello without quotes! That is what you should be passing to the proper form of the .format call...!
even thought the requestor of the original question was wrong in using the .format structure - I believe he's still right about one thing - the behavior in Python3 is different when having a value that equals None
Example
fmt = '{:^9}|{:^13}|{:^18}'
data = [1, None, 'test']
print(fmt.format(*data))
Python2.7
$ python2.7 test
1 | None | test
In Python3.6
python3.6 test
Traceback (most recent call last):
File "test", line 5, in <module>
print(fmt.format(*data))
TypeError: unsupported format string passed to NoneType.__format__
But if we remove the format's features of column-width
fmt = '{}|{}|{}'
data = [1, None, 'test']
print(fmt.format(*data))
OR convert all values to Strings using !s
fmt = '{!s:^9}|{!s:^13}|{!s:^18}'
It works just fine in both versions ...

Misleading `ValueError` on bad formatting in python 2.7

When I try the following wrong code:
not_float = [1, 2, 3]
"{:.6f}".format(not_float)
I get the following misleading ValueError:
ValueError: Unknown format code 'f' for object of type 'str'
It is misleading, since it might make me think not_float is a string. Same message occurs for other non_float types, such as NoneType, tuple, etc. Do you have any idea why? And: should I expect this error message no matter what the type of non_float is, as long as it does not provide some formatting method for f?
On the other hand, trying:
non_date = 3
"{:%Y}".format(non_date)
brings
ValueError: Invalid conversion specification
which is less informative but also less misleading.
The str.format() method, and the format() function, call the .__format__() method of the objects that are being passed in, passing along everything after the : colon (.6f in this case).
The default object.__format__() implementation of that method is to call str(self) then apply format() on that result. This is implemented in C, but in Python that'd look like:
def __format__(self, fmt):
return format(str(self), fmt)
It is this call that throws the exception. For a list object, for example:
>>> not_float.__format__('.6f')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
because this is functionally the same as:
>>> format(str(not_float), '.6f')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'f' for object of type 'str'
Integers have a custom .__format__ implementation instead; it does not use str() internally because there are integer-specific formatting options. It turns the value into a string differently. As a result, it throws a different exception because it doesn't recognize %Y as a valid formatting string.
The error message could certainly be improved; an open Python bug discusses this issue. Because of changes in how all this works the problem is no longer an issue in Python 3.4 though; if the format string is empty .__format__() will no longer be called.

__class_ data member in python, how it is different from static data member in java

i am trying to execute following code to understand Class data member in python, but it is throwing StopIteration error,
class PizzaShop():
pizza_stock = 10
def get_pizza(self):
while not PizzaShop.pizza_stock:
PizzaShop.pizza_stock -= 1
yield "take yours pizza order, total pizzas left {}".format(PizzaShop.pizza_stock)
mypizza_shop = PizzaShop()
pizza_order = mypizza_shop.get_pizza()
print "{}".format(repr(pizza_order.next()))
i am expecting that it should first print some message and then any exception
i am using python 2.7, ubuntu 32bits os
output:
Traceback (most recent call last):
File "/home/scott/pythonfiles/core_python/pizza.py", line 10, in <module>
print "{}".format(repr(pizza_order.next()))
StopIteration
The problem is this line
while not PizzaShop.pizza_stock:
This will stop immediately if pizza_stock is nonzero. Which it always is. You probably intended to write
while PizzaShop.pizza_stock:
Anyway, if you want to find the details on how values, classes, etc. behave in Python, you should check the docs. It's very different from Java.
P.S. The following is unnecessary as str.format has a shorthand for calling repr. Also, you shouldn't call magic methods like .next directly. Use the builtin next() instead.
print "{}".format(repr(pizza_order.next()))
Should be
print "{!r}".format(next(pizza_order))

Categories

Resources