How to Create a Tuple With Only One Element

How to create a tuple with only one element

why is a tuple converted to a string when it only contains a single string?

a = [('a'), ('b'), ('c', 'd')]

Because those first two elements aren't tuples; they're just strings. The parenthesis don't automatically make them tuples. You have to add a comma after the string to indicate to python that it should be a tuple.

>>> type( ('a') )
<type 'str'>

>>> type( ('a',) )
<type 'tuple'>

To fix your example code, add commas here:

>>> a = [('a',), ('b',), ('c', 'd')]

^ ^

From the Python 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). Ugly, but effective.

If you truly hate the trailing comma syntax, a workaround is to pass a list to the tuple() function:

x = tuple(['a'])

Create a single element tuple of tuple

I don't really see the issue, this adheres to the documentation:

class tuple(object)
| tuple() -> empty tuple
| tuple(iterable) -> tuple initialized from iterable's items
|
| If the argument is a tuple, the return value is the same object.

So, list('abc') always evaluates to ['a', 'b', 'c'] which is an iterable.

So in the first example (tuple(['a', 'b', 'c'])), the result is a tuple initialised from the iterable's items. I.e. ('a', 'b', 'c').

The second example takes the result of the first example (a tuple) and passes it into the tuple() function once more. As the documentation states (last line), the return value when passed a tuple is the same object which matches with our result.

And for the third, once more, the docs tell us what we need to know:

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).


Finally, your last two examples (tuple([1]) and tuple([1],)) both produce a one-element tuple, because you are passing an iterable of length one. The docs once again state (at top): a tuple is initialized from iterable's items.

So, to conclude, the case where you need a comma is when you want to create a tuple with one element. However, if passing an iterable of length one, this is not necessary as Python understands that you are not evaluating an expression.


For completeness, the reason this awkward syntax is unavoidable is because statements like: (1 + 2) * 3 would evaluate to (3, 3, 3) rather than the expected 9. So instead, you must go out of your way through adding a comma: (1 + 2,) * 3 to get the result of (3, 3, 3) which makes perfect sense.

How to perfectly convert one-element list to tuple in Python?

This is such a common question that the Python Wiki has a page dedicated to it:

One Element Tuples

One-element tuples look like:

1,

The essential element here is the trailing comma. As for any
expression, parentheses are optional, so you may also write
one-element tuples like

(1,)

but it is the comma, not the parentheses, that define the tuple.

How to construct a tuple with only one element in standard ML?

Can we distinct 'a and a tuple with only one element of type 'a in SML?

Yes, you can.

Unlike Python, there isn't any special (1,) syntax. But since tuples are equivalent to records with numbered fields, you can create a record with exactly one field named 1 and access it using the #1 macro for getting the first value of a tuple:

- val foo = { 1 = 42 };
val foo = {1=42} : {1:int}

- #1 foo;
val it = 42 : int

You can see that this is actually a 1-tuple by trying to annotate a regular 2-tuple as a record:

- (3.14, "Hello") : { 1 : real, 2 : string };
val it = (3.14,"Hello") : real * string

what's type signature of it?

The type would be { 1 : 'a }. You can preserve the type parameter like this:

type 'a one = { 1 : 'a };

You could get something similar using a datatype:

datatype 'a one = One of 'a
fun fromOne (One x) = x

I think those would use the same amount of memory.

Python tuples: How can i have only one element as pair?

You can have a one-element tuple, you just need the trailing , like in your second example.

Parenthesis without , mean whatever inside is just a normal expression and can sometimes be used to split a long expression into several lines: How can I do a line break (line continuation) in Python?

Create a new Tuple with one element modified

def item(i, v):
if i != 1: return v
return strangestuff(v)

for row in rows:
t = tuple(item(i, c.InnerText)
for i, c in enumerate(row.Descendants[TableCell]())
)

Why single element tuple is interpreted as that element in python?

A single element tuple is never treated as the contained element. Parentheses are mostly useful for grouping, not for creating tuples; a comma does that.

Why don't they just print (1,) as (1)?

Probably because printing a builtin container type gives a representation that can be used to recreate the container object via , say eval:

The docs for __repr__ provides some clarity on this:

If at all possible, this should look like a valid Python expression
that could be used to recreate an object with the same value

Answering your question, (1) is just integer 1 with a grouping parenthesis. In order to recreate the singleton tuple via its representation, it has to be printed as (1,) which is the valid syntax for creating the tuple.

>>> t = '(1,)'
>>> i = '(1)'
>>> eval(t)
(1,) # tuple
>>> eval(i)
1 # int

How to pass tuple with one element as param in sql query Python?

I don't think what you are trying to do is possible in the Python3 version of the MySQL Connector. The code converts Python dict values into SQL syntax, depending on the Python type. But in the connector code, only scalar types are supported, no list or tuple. See https://github.com/mysql/mysql-connector-python/blob/master/lib/mysql/connector/conversion.py#L221-L372

I'd use the solution in the accepted answer to imploding a list for use in a python MySQLDB IN clause, which is to generate N placeholders for the number of items in your list, plus one more placeholder for the value to compare to created_at. Then merge the list with the date value and pass that.

ids = ['1232a4df-5849-46c2-8c76-74fe74168d82'] # list of ids
id_placeholders = ','.join(['%s'] * len(ids))
query = f'''
SELECT *
FROM mytable
WHERE
id IN ({id_placeholders})
AND created_at > %s
'''

params = ids
params.append('2019-10-31 00:00:00')

cursor.execute(query, params)

Cannot access element in tuple

You need to create the dictionary before you enter the loop and you need to execute the return statement after you exit the loop.

def getGrades(tuples):

grade_dict = dict()

for tup in tuples:
(name, midterm1, midterm2, midterm3, final) = tup

# get average of midterm grades
average_midterm = (midterm1 + midterm2 + midterm3) / 3.0

# replace if average is better
if average_midterm > midterm1:
midterm1 = average_midterm

if average_midterm > midterm2:
midterm2 = average_midterm

if average_midterm > midterm3:
midterm3 = average_midterm

# weight grades
midterm1_weight = midterm1 * 0.20
midterm2_weight = midterm2 * 0.20
midterm3_weight = midterm3 * 0.20
final_weight = final * 0.40

# calculate grade
grade = midterm1_weight + midterm2_weight + midterm3_weight + final_weight
grade = math.floor(grade)

grade_dict[name] = grade

return grade_dict


Related Topics



Leave a reply



Submit