why are the following declarations not the same? - python

I assumed that I defined a tuple. luckily it worked for a long time.
In one specific point it broke --> figured out that it was actually not a tuple.
In the end I expected a tuple with 1 string inside like this
("expected tuple")
Confusing, please explain
if any(key in [tuple("expect tuple"), tuple(("expect tuple"),),("expect tuple")] for key in [(("expect tuple"),)]):
print("same")

A tuple with a single element must be written like this:
("expected tuple",)
Without the , it'd be interpreted as a value surrounded by brackets, but not an actual tuple. We don't have this problem for tuples with more than one element, in those cases we don't need the trailing comma.

Related

why there is no error for a= [10,] but error for [10,,] in python?

why is there no error for a = [10,] but error for [10,,] in Python ?
what is interpreter expecting from comma/s in both the cases?
I understand it's more of a syntax error but there has to rationale/logical explanation of this.
Of course there is a logical explanation.
Many people, when writing a list, leave in the extra final comma, as in
lst = [1,2,3,4,]
So, Python allows that and ignores a final comma. But you can't have an empty entry in the MIDDLE of a list.
In python list we cannot have an empty entry in middle of two values. We need to put either any value of any datatype or None.
-->In this the pyhton will ignore the last comma as no value is after that.
lst = [10,20,30,]
--> It shows there is an empty entry before the end of list and its not permissible. Thats why it will throw an error.
lst = [10,,]

TypeError: can only concatenate tuple (not "str") to tuple Error

Just trying to make a tuple to add to make my main programming. Anyway this is my code-
print"I have a few things to finish my exam, but i might need more"
exam=("Brain","Computer","python")
print "The stuff i have are:"
for stuff in exam:
print stuff
print"I still need my previous assignments!"
extra=("Assignments")
exam += extra
for stuff in exam:
print stuff
I keep getting the can only concatenate tuple error. Anyone have a clue my issue/how to fix it? Greatly appreciated.
Well that is because according to the python doc
Tuples are constructed by the comma operator (not within square brackets), with or without enclosing parentheses, but an empty tuple must have the enclosing parentheses, such as a, b, c or (). A single item tuple must have a trailing comma, such as (d,).
so if you do this to your code it has to work
extra = "Assignments",
or
extra = ("Assignments",)

Explain a python construction

I have a list of tuples in 'tups' and have applied the following code to filter. The list of tuples have the format [(floata,stra1,stra2),(floatb,strb1,strb2),...etc]
keys=sorted({t[2] for t in tups})
for key in keys:
group=filter(lambda t: t[2]==key,tups)
print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))
Initially I thought the curly brackets was a mistake and changed them to square brackets. I did not get a syntax error but the code did not work. As a last resort I changed the brackets back and everything was fine. Can someone explain the construction. Is this a dictionary comprehension? Where is this explained in the documentation?
If you mean the curly brackets in the first line, this is a set comprehension. This will create a set of the third item from every tuple in tups. A set is similar to a list, but without order, and therefore cannot contain duplicates.
If you mean the brackets in the string, this is just new-style string formatting. Calling str.format() changes those braces into the passed values.
Before Python 2.6, you would have used:
print '%s:\n\tmax: %s\n\tmin: %s' % (key,max(group),min(group))
to format a string using placeholders (the %s).
Since Python 2.6, you can use the {} syntax for the placeholder and .format instead:
print '{}:\n\tmax: {}\n\tmin: {}'.format(key,max(group),min(group))
or using positional arguments:
print '{0}:\n\tmax: {2}\n\tmin: {1}'.format(key,min(group),max(group))
(notice that I changed the order of the arguments, but the output is the same: we used {2} to represent the third argument...)
Just an advice: when you get a lot of arguments, it's easier to name them, as:
print '{key}:\n\tmax: {groupmax}\n\tmin: {groupmin}'.format(key=key,groupmin=min(group),groupmax=max(group))
The .format syntax is more powerful than the % one: examples are available in the documentation.

Python: how to ensure method gets a list

I have a method that takes a list of strings. Unfortunately, if the list is only one item long, Python treats this list as a string.
This post has a method for checking whether something is a string, and converting it to a list if it is:
Python: How to define a function that gets a list of strings OR a string
But this seems an incredibly redundant way of getting the item that I passed in as a list to in fact be a list. Is there a better way?
You are probably using tuples, not lists, and forgetting to add the comma to the one-item tuple literal(s). ('foo') is interpreted as simply 'foo' which would match what you are saying. However, adding a comma to one-item tuple literals will solve this. ('foo',) returns, well, ('foo',).
I'm not sure I believe you, python shouldn't behave that way, and it doesn't appear to:
>>> def foo(lst):
print type(lst)
>>> foo(['bar'])
<type 'list'>
That post was about a different thing, they wanted the ability to pass a single string or a list of strings and handle both cases as if they were lists of strings. If you're only passing in a list, always treating it as a list should be fine.
Python shouldn't do that with a list. A singleton tuple, though, has syntax different from singleton lists:
(1) == 1 # (1) is 1
[1] != 1 # [1] is a singleton list
(1,) != 1 # (1,) is a singleton tuple
You are mistaken. Python does no such transformation to lists of a single element.
Double, Triple check that you are putting the [] around the the item you are passing.
If you still can't get it working show us the code!

How to stop sqlite from return unicode symbol

I could be mistaken but since I backtracked to python 2.7 from 3.2 I've noticed something sqlite3 is doing that I don't like...
When I use to use my cursor.fetch method it would return (1, x, x, x) from my table
but in 2.7 its returning (1, u'x' ,u'x' ,u'x')
How do I get it to stop returning that 'u' in my queries? I need to store the return values in variables and it's kind of irritating having to problem solve this.
Edit: Through a little research I've found a way...
db.text_factory = str
if there is a better way please inform me as I really don't even know what this method does, hate to be changing the wrong thing
Sigh.
(1, u'x' ,u'x' ,u'x') is a tuple. That tuple contains four elements. One of them is an integer, the other three are unicode strings, as indicated by the u.
If you print the entire tuple at once, it will look like the above. But that's a silly thing to do, because presumably you actually want to do something with the contents of the tuple, not the tuple itself.
If you did print result[1], you would see the output is just x: the u is not shown when you actually print it. That is the correct behaviour.
If you use the code you post, as soon as you retrieve a non-ASCII value from your datastore - someone whose name contains an accented character, for example - things will go horribly wrong.

Categories