Python unpack list of tuples

Tutorialdeep » knowhow » Python Faqs » How to Unpack Tuple Pairs in List Using Python

  • By : Roshan Parihar
  • / In : Python Faqs
  • < >

In this tutorial, learn how to unpack tuple pairs in list with Python. The short answer is to use the loop and print each element one-by-one. The list contains tuple elements with two in pairs. Get each tuple with paired elements after unpacking using the methods given here.

The list is a similar element as that or array in other programming languages. Here, the list elements are tuple enclosed within the round bracket. The tuple elements are paired within the list with two-element pairs.

Unpack Tuple Pairs in List With For Loop in Python

If you want to unpack the tuple pairs in the list, you have to use the for loop to the list.

The example contains the 3 tuples as the list elements. To perform for loop with the list, you have to follow the below-given example.

mynewTuple = [["Ram", 23], [10, "Dara"], [17, "Raju"]]; for t in mynewTuple: print[t];

mynewTuple = [["Ram", 23], [10, "Dara"], [17, "Raju"]];

Output

[‘Ram’, 23] [10, ‘Dara’] [17, ‘Raju’]

The above example contains a list of 3 tuple elements. Each tuple contains 2 elements in pairs. After you perform loop iteration with the list in Python, you will get individual tuples in the output.

Use While Loop to Access and Print Each Tuple Elements in List in Python

In addition to for loop, you can also unpack by using while loop. To perform while loop with this list, you have to find the length of the list in Python to perform iteration.

After the iteration, you will get the same number of the tuple as you get with for loop above. See the example below to get the idea of how to use a while loop for getting the tuple elements.

mynewTuple = [["Ram", 23], [10, "Dara"], [17, "Raju"]]; t=0; while t < len[mynewTuple]: print[mynewTuple[t]] t += 1

mynewTuple = [["Ram", 23], [10, "Dara"], [17, "Raju"]];

while t

Chủ Đề