I have just started to learn python and following the docs on tuples, I came across this snippet,
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Following this I ran following snippet,
>>> foo=1,2,3,
>>> len(foo)
3
>>> foo
(1, 2, 3)
Why does singleton prints with an trailing comma , where as foo seems to trim it ?
Beacause ("Hello") is not a tuple, it is same as "Hello".
>>> ("Hello")
'Hello'
in order to distinguish tuple with single element from a simple expression in () a , is necessary. Whereas (1,2,3) is clearly a collection of items, and as they are enclosed by () it can easily be inferred as a tuple, hence no need for a trailing ,.
because you define variable"singleton" as ("hello",), you don't need comma to end it, and for "foo", you define it, so it shows as what you defined
Related
Is there a way to disable breaking string with list. For example:
>>> a = "foo"
>>> b = list()
>>> b.append(list(a))
>>> b
>>>[['f', 'o', 'o']]
Is there a way to have a list inside of a list with string that is not "broken", for example [["foo"],["bar"]]?
Very esay:
>>> a = "foo"
>>> b = list()
>>> b.append([a])
>>> b
[['foo']]
Do this:
>>> a = "foo"
>>> b = list()
>>> b.append([a])
>>> b
[["foo"]]
The reason this happens is that the list function works by taking each element of the sequence you pass it and putting them in a list. A string in Python is a sequence, the elements of the sequence are the individual characters.
Having this abstract concept of a "sequence" means that a lot of Python functions can work on multiple data types, as long as they accept a sequence. Once you get used to this idea, hopefully you'll start finding this concept more useful than surprising.
you sound like you want to break on word boundaries instead of on each letter.
Try something like
a = "foo bar"
b = list()
b.append(a.split(' ')) # [['foo', 'bar']]
Example with RegEx (to support multiple consecutive spaces) :
import re
a = "foo bar"
b.append(re.split(r'\s+', a)) # [['foo', 'bar']]
This question already has answers here:
Why does adding a trailing comma after an expression create a tuple?
(6 answers)
Closed 6 years ago.
How python initializes a tuple object ?
For example, when I create an object like
>>> object = ('Shark')
It shows type of object as str
>>> type(object)
<type 'str'>
While, if I create an object like
>>> object = ('Shark',)
It displays its type as a tuple
>>> type(object)
<type 'tuple'>
Why so ?? How exactly python creates/initializes a tuple, str objects ?
From docs:
A special problem is the construction of tuples containing 0 or 1
items: the syntax has some extra quirks to accommodate these. Empty
tuples are constructed by an empty pair of parentheses; a tuple with
one item is constructed by following a value with a comma (it is not
sufficient to enclose a single value in parentheses).
So, without a trailing , these two statements are equivalent:
>>> x = 1
>>> x
1
>>> x = (1)
>>> x
1
But these are all tuples:
>>> x = 1, #or (1,)
>>> x
(1,)
>>> x = 1, 2, 3 #or (1, 2, 3)
>>> x
(1, 2, 3)
An expression enclosed in parens is just that expression (it's like the parens in a math expression, like (2+2)*4).
But, if you add a trailing comma, or if there's more than one element inside the parens separated by commas, it will become a tuple. Also, you will get an empty tuple if you write ().
Anything enclosed inside double-quotes or single-quotes will be treated as a string in Python. There's no distinction between the two-- like in PHP, that variables inside the double-quoted strings will actually be evaluated and single-quotes will display as it is.
Anything enclosed inside an opening parenthesis and closing parenthesis will be treated as tuples. However, if only one object has been placed in the tuple, it'll be treated as the object's type. For instance:
>>> a = (9)
>>> type(a)
<class 'int'>
>>>
>>> a = ([9])
>>> type(a)
<class 'list'>
>>>
>>> a = ('hello!')
>>> type(a)
<class 'str'>
>>>
>>> a = {'a':1, 'b':1}
>>> type(a)
<class 'dict'>
>>>
Note that the length of the object doesn't matter (the object placed inside of the tuple, not the tuple itself).
Now, if you were to place a comma after the object inside of the tuple, Python will presume that there's another object coming and it'll treat it as if it were a tuple and not give you an error. Also, note that the default object used by Python to store a number of things is also a tuple-- meaning that even if you don't enclose an expression in parenthesis, it'll do it by default for you:
>>> a = 9, 8, 7
>>> a
(9, 8, 7)
>>> type(a)
<class 'tuple'>
>>>
>>> a = 'Hello', 'Python', 'Typle'
>>> a
('Hello', 'Python', 'Typle')
>>> type(a)
<class 'tuple'>
>>>
math.pow (base/exponent) requires comma separated values...working fine for pre-assigned values, but having trouble with user-submitted values (experimenting in command line). Help appreciated as I want to develop this kind of thing eventually making a basic math test.
exp = int(raw_input())
while exp:
print math.pow(int(raw_input))
The errors I'm getting are
ValueError: invalid literal for int() with base 10: '2,3' (which seems weird as this is an exponent, not log function...)
When I try:
exp = (raw_input())
while exp:
print math.pow(exp)
I get error:
pow expected 2 arguments, got 1
Even though I'm submitting 2,3 for example (with comma).
I also tried concatenating the input with .split, but got error regarding pow requiring integers, not "list."
When you enter an input with a comma, you get a tuple. You can either use
eval(raw_input())
Or just
input()
To get this from a string to a usable format. Once you have a tuple, you can use * notation to "unpack" the tuple. So instead of calling math.pow((2, 3)), where the one argument is the tuple (2, 3), you will be calling math.pow(2, 3).
>>> exp = input()
2, 3
>>> math.pow(*exp)
8.0
"2,3" is a string, passing this to a function won't make it act like two different parameters separated by ,(as you expected).
>>> def func(arg):
... print arg
...
>>> func('a, b')
a, b # arg is a variable that stores the passed string
You should convert that string into two numbers first by splitting it at comma first and then applying int() to each if it's item.
>>> import math
>>> math.pow(*map(int, '2,3'.split(',')))
8.0
First split the string at ',' using str.split:
>>> '2,3'.split(',')
['2', '3'] #str.split returns a list
Now as we need integers so apply int() to each value:
>>> map(int, '2,3'.split(',')) #apply int() to each item of the list ['2', '3']
[2, 3]
Now as pow expects two arguments so you can use * notation to unpack this list and pass
the items to math.pow.
>>> math.pow(*[2 , 3])
8.0
A even simpler way would be to use sequence unpacking:
>>> a, b = [2, 3]
>>> math.pow(a, b)
8.0
There's another tool in python library that can convert comma separated items in a string into a tuple:
>>> from ast import literal_eval
>>> literal_eval('1, 2')
(1, 2)
>>> a,b = literal_eval('1, 2')
>>> a
1
>>> b
2
Apologies if this doesn't make any sense, I'm very new to Python!
From testing in an interpreter, I can see that list() and [] both produce an empty list:
>>> list()
[]
>>> []
[]
From what I've learned so far, the only way to create an object is to call its constructor (__init__), but I don't see this happening when I just type []. So by executing [], is Python then mapping that to a call to list()?
Those two constructs are handled quite differently:
>>> import dis
>>> def f(): return []
...
>>> dis.dis(f)
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> def f(): return list()
...
>>> dis.dis(f)
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
>>>
The [] form constructs a list using the opcode BUILD_LIST, whereas the list() form calls the list object's constructor.
No, Python does not call list(), or you could affect what type [] creates by assigning to list, which you cant:
>>> import __builtin__
>>> __builtin__.list = set
>>> list()
set([])
>>> []
[]
[] is syntax for creating a list. It's a builtin type and it has special syntax, just like dicts and strings and ints and floats and lots of other types.
Creating instances of types can also be done by calling the type, like list() -- which will in turn call the type's constructor and initializer for you. Calling the initializer (__init__) directly does not create a new instance of the type. Calling the constructor (__new__) does, but you should not be calling it directly.
I started learning python yesterday....
I guess you would have to say its internally mapped
>>> a = []
>>> type(a)
<type 'list'>
>>> a = list()
>>> type(a)
<type 'list'>
What are the key differences between using list() and []?
The most obvious and visible key difference between list() and [] is the syntax. Putting the syntax aside for a minute here, someone whose new or intermediately exposed to python might argue that they’re both lists or derive from the same class; that is true. Which furthermore increases the importance of understanding the key differences of both, most of which are outlined below.
list() is a function and [] is literal syntax.
Let’s take a look at what happens when we call list() and [] respectively through the disassembler.
>>> import dis
>>> print(dis.dis(lambda: list()))
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0 (0 positional, 0 keyword pair)
6 RETURN_VALUE
None
>>> print(dis.dis(lambda: []))
1 0 BUILD_LIST 0
3 RETURN_VALUE
None
The output from the disassembler above shows that the literal syntax version doesn’t require a global lookup, denoted by the op code LOAD_GLOBAL or a function call, denoted by the op code CALL_FUNCTION.
As a result, literal syntax is faster than it’s counterpart. – Let’s take a second and look at the timings below.
import timeit
>>> timeit.timeit('[]', number=10**4)
0.0014592369552701712
>>> timeit.timeit('list()', number=10**4)
0.0033833282068371773
On another note it’s equally important and worth pointing out that literal syntax, [] does not unpack values. An example of unpacking is shown below.
>>> list('abc') # unpacks value
['a', 'b', 'c']
>>> ['abc'] # value remains packed
['abc']
What’s a literal in python?
Literals are notations or a way of writing constant or raw variable values which python recognises as built-in types.
Sourced from my post on PythonRight - what's the difference between list and [].
In addition to the other answers, from the Language Reference:
A list display is a possibly empty series of expressions enclosed in square brackets:
list_display ::= "[" [expression_list | list_comprehension] "]"
...
A list display yields a new list object.
It does not explicitly mention how "yielding a new list object" is implemented. It could well be a call to the list() constructor, like you mentioned. Or maybe lists, being so elementary, get special treatment, and list() is actually mapped to something different entirely.
Either way, [] is certainly not mapped to a call to the constructor of the type named __builtins__.list, because redefining that type still causes [] to return an actual list, as other answerers have shown.
Python, like most programming langauges, has something called literals, meaning that special syntax can be used to write out some of the most important types of values. Very little of this is necessary, but it makes it easier to use Python that we can write literals.
>>> 0
0
>>> int()
0
>>> 5
5
>>> int('5') # I'm using a string literal here though!
5
>>> 0.0
0.0
>>> float()
0.0
>>> ""
''
>>> str()
''
>>> u""
u''
>>> unicode()
u''
>>> ()
()
>>> tuple()
()
>>> {}
{}
>>> dict()
{}
When we make our own types (classes), we create instances of them using their constructors, like list for lists. When we use literals, it's sort of like syntactic sugar for calling list, but in reality it calls that same basic things behind the scene.
Since :
class list(object):
"""
list() -> new empty list
list(iterable) -> new list initialized from iterable's items
"""
If the element in your lists is an iterable (i.e. a str), the list() and [] don't work the same way.
So
>>> a = ['ab']
>>> b = list('ab')
>>> a[0]
'ab'
>>> b[0]
'a'
I know this is one way, by placing a comma:
>>> empty = ()
>>> singleton = 'hello', # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
Source: http://docs.python.org/tutorial/datastructures.html
Are there more ways to define a tuple with only 1 item?
>>> tuple(['hello'])
('hello',)
But the built-in syntax is there for a reason.
Even though you can define a tuple as 'hello', I think it would be easy for someone to possibly miss the trailing comma if they were reading your code. I definitely prefer
('hello',) from a readability stand-point.
singleton = ('hello',)
This is more clear I guess, and #jleedev even more clear. But I like the method you used the best:
singleton = 'hello',
Another one is
>>> (1, 2)[0:1]
(1,)
A very obfuscated way, but it is an alternative...