9/25/2023 0 Comments Tuple unpackingThe following expression swaps the values of two variables, x and y. X= 20, y= 10 Code language: Python ( python ) Print( f'x= ') Code language: Python ( python ) Traditionally, to swap the values of two variables, you would use a temporary variable like this: x = 10 Using unpacking tuple to swap values of two variables In the above example, the x, y, and z variables will take the values 10, 20, and 30 respectively. Print(type(numbers)) Code language: Python ( python ) You can quickly check its type as follows: numbers = 10, 20, 30 The right side is a tuple of three integers 10, 20, and 30. See another example: x, y ,z = 10, 20, 30 Code language: Python ( python ) In the above example, x will take 1 and y will take 2. The expression assigns the tuple elements on the right side (1, 2) to each variable on the left side (x, y) based on the relative position of each element. The right side is also a tuple of two integers 1 and 2. The left side: x, y Code language: Python ( python ) For example: x, y = ( 1, 2) Code language: Python ( python ) Unpacking a tuple means splitting the tuple’s elements into individual variables. Note that the following is an integer, not a tuple: ( 1) Code language: Python ( python ) Unpacking a tuple It’s equivalent to the following: ( 1, ) Code language: Python ( python ) The following example illustrates how to define a tuple with one element: 1, Code language: Python ( python ) To define a tuple with only one element, you still need to use a comma. In addition, you can use the tuple() constructor like this: tuple() Code language: Python ( python ) Python also uses the parentheses to create an empty tuple: () Code language: Python ( python ) Python uses the parentheses to make the tuple clearer: ( 1, 2) Code language: Python ( python ) For example, the following defines a tuple with two elements: 1, 2 Code language: Python ( python ) Python defines a tuple using commas ( ,), not parentheses (). Summary: in this tutorial, you’ll learn how to unpack tuples in Python.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |