The python tuple ... is not a tuple? What does the comma do?

I searched the code in my course material and had to write a function that adds the value 99 to either k listor k tuple. The final code is as follows:

def f(l):
    print(l)
    l += 99,
    print(l)

f([1,2,3])
f((1,2,3))

This was used to show something else, but I hung up the line a bit l += 99,. What this means is, create iterability that contains 99 and list, and also tuplesupports the simple “adding” of such an object to create a new instance / add a new element.

That I really don't understand what exactly is created using the syntax element,? If I do the type job x = 99,, then it type(x)will tuple, but if I try to start x = tuple(99)it will fail, because 99 will not be exterminated. That's it:

  • Some kind of intermediate iterable created using syntax element,?
  • Is there a special function defined that would allow calling tuplewithout an iteration and is somehow ,matched with this?

Edit: In case anyone asks why the accepted answer is this: this is the explanation of my second question. I should have clarified my question, but what +=is what really confused me, and this answer contains information about it.

+4
3

element, "" tuple, - ( tuple, , ).

, . :

l += (99,)

... . , . AINE , :

list((99,))
tuple((99,))
set((99,))

, [] list:

list([99])
tuple([99])
set([99])

... , 99, tuple :

list(99,)
tuple(99,)
set(99,)

, , tuple() . element, (element,) - [] list {} dict set ( list, dict, set ):

[99] #list 
(99,) #tuple -  note the comma is required
{99} #set

, , (+ =) a list tuple. : :

l = [1]  
l + (2,) # error

, , -, . :

l += [2]
l += list((2,))

, ( , ), .

+3

= , , , . tuple(99) , tuple ; , x tuple.

99, ; , . , foo((99,100)) foo , foo(99,100) foo int.

+5

The tuple constructor requires iteration (as stated in the error message), so for execution x = tuple(99)you need to include it in the iterable list, for example:

x = tuple([99])

or

x = tuple((99,))
+3
source

Source: https://habr.com/ru/post/1663362/


All Articles