Use the type() function to display the list_to_tuple_example variable’s type. list_to_tuple_example = tuple(example_list) To convert example_list into a tuple, pass example_list as an argument of the tuple() method, and assign the result to a new variable. In Python, a list contains comma-separated items wrapped in square brackets. The following sections show you how to convert Python’s collection types into a tuple. Python collection types include lists, tuples, sets, and dictionaries. The tuple() function converts the four Python collection types into a tuple. The difference occurs because the first example includes a trailing comma, while the second example does not. The Python interpreter confirms that the day variable does not store a tuple, and instead stores a string: Now, store the same value in the day variable, but exclude the trailing comma. The Python interpreter confirms that day contains a tuple with a single value. Use the type() function to display the day variable’s type. For example, create the following tuple to store a single string. If you don’t include the comma, Python does not store the value as a tuple. To store a single value, or singleton in a tuple, you must include a comma when assigning the value to a variable. If you print example_tuple, the following is returned: print(example_tuple)Ĭreate a Tuple with a Single Value (Singleton) Use the built-in tuple() method to create a new tuple: example_tuple = tuple() You can exclude the parentheses when creating a tuple with multiple values: example_tuple = 1, 2, 3 Create a Python TupleĪ Python tuple can be created in the following ways:Ĭreate an empty tuple with an empty pair of parentheses: example_tuple = ()Ĭreate a tuple with multiple values that are separated with commas: example_tuple = (1, 2, 3) The section below covers the syntax for each way that you can create a Python tuple. However, there are a few syntax quirks to keep in mind when working with tuples in Python. The syntax to create a Python tuple is made up of your tuple values that are comma separated and enclosed in parentheses. You should have Python 3.0 installed on your machine to follow along with the examples in this guide.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |