If we define __str__
method in a class:
class Point(): def __init__(self, x, y): self.x = x self.y = y def __str__(self, key): return '{}, {}'.format(self.x, self.y)
We will be able to define how to convert the object to the str
class (into a string):
a = Point(1, 1) b = str(a) print(b)
I know that we can define the string representation of a custom-defined object, but how do we define the list —more precisely, tuple— representation of an object?
Python's built-in function tuple() converts any sequence object to tuple. If it is a string, each character is treated as a string and inserted in tuple separated by commas.
To convert Python Set to Tuple, use the tuple() method. The tuple() function takes an iterator as a parameter, and in our case, it is a set, and it returns a tuple.
Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.
1) Using tuple() builtin function tuple () function can take any iterable as an argument and convert it into a tuple object. As you wish to convert a python list to a tuple, you can pass the entire list as a parameter within the tuple() function, and it will return the tuple data type as an output.
The tuple
"function" (it's really a type, but that means you can call it like a function) will take any iterable, including an iterator, as its argument. So if you want to convert your object to a tuple, just make sure it's iterable. This means implementing an __iter__
method, which should be a generator function (one whose body contains one or more yield
expressions). e.g.
>>> class SquaresTo: ... def __init__(self, n): ... self.n = n ... def __iter__(self): ... for i in range(self.n): ... yield i * i ... >>> s = SquaresTo(5) >>> tuple(s) (0, 1, 4, 9, 16) >>> list(s) [0, 1, 4, 9, 16] >>> sum(s) 30
You can see from the example that several Python functions/types will take an iterable as their argument and use the sequence of values that it generates in producing a result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With