How do you access elements in a list of tuples in Python?

Python | Accessing nth element from tuples in list

While working with tuples, we store different data as different tuple elements. Sometimes, there is a need to print a specific information from the tuple. For instance, a piece of code would want just names to be printed of all the student data. Lets discuss certain ways how one can achieve solutions to this problem.

Method #1 : Using list comprehension
List comprehension is the simplest way in which this problem can be solved. We can just iterate over only the specific index value in all the index and store it in a list and print it after that.




# Python3 code to demonstrate
# get nth tuple element from list
# using list comprehension
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
# printing original list
print ("The original list is : " + str(test_list))
# using list comprehension to get names
res = [lis[1] for lis in test_list]
# printing result
print ("List with only nth tuple element (i.e names) : " + str(res))

Output :

The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']

Method #2 : Using map() + itemgetter()
map() coupled with itemgetter() can perform this task in more simpler way. map() maps all the element we access using itemgetter() and returns the result.




# Python3 code to demonstrate
# get nth tuple element from list
# using map() + itergetter()
from operator import itemgetter
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
# printing original list
print ("The original list is : " + str(test_list))
# using map() + itergetter() to get names
res = list(map(itemgetter(1), test_list))
# printing result
print ("List with only nth tuple element (i.e names) : " + str(res))

Output :

The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']

Method #3 : Using zip()
The most conventional and pythonic way to perform this particular task is using this function. This collects all the nth tuple elements into a single container and returns the result. This only works for Python 2.




# Python code to demonstrate
# get nth tuple element from list
# using zip()
# initializing list of tuples
test_list = [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)]
# printing original list
print ("The original list is : " + str(test_list))
# using zip() to get names
res = list(zip(*test_list)[1])
# printing result
print ("List with only nth tuple element (i.e names) : " + str(res))

Output :

The original list is : [(1, 'Rash', 21), (2, 'Varsha', 20), (3, 'Kil', 19)] List with only nth tuple element (i.e names) : ['Rash', 'Varsha', 'Kil']




Article Tags :
Python
Python list-programs
python-list
python-tuple
Practice Tags :
python-list
Read Full Article

Lists and Tuples in Python

by John Sturtz basics python
Mark as Completed
Tweet Share Email

Table of Contents

Remove ads

Watch Now This tutorial has a related video course created by the Real Python team. Watch it together with the written tutorial to deepen your understanding: Lists and Tuples in Python

Lists and tuples are arguably Python’s most versatile, useful data types. You will find them in virtually every nontrivial Python program.

Here’s what you’ll learn in this tutorial: You’ll cover the important characteristics of lists and tuples. You’ll learn how to define them and how to manipulate them. When you’re finished, you should have a good feel for when and how to use these object types in a Python program.

Take the Quiz: Test your knowledge with our interactive “Python Lists and Tuples” quiz. Upon completion you will receive a score so you can track your learning progress over time:

Take the Quiz »

What is Python List and Tuple?

Python List is a data structure that maintains an ordered collection of mutable data elements.

list-name = [ item1, item2, ....., itemN]

The elements in the list are enclosed within square brackets [].

Python Tuple is an immutable data structure whose elements are enclosed within parenthesis ().

tuple-name = (item1, item2, ...., itemN)

Python List of Tuples

We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.

Example:

LT_data = [(1,2,3),('S','P','Q')] print("List of Tuples:\n",LT_data)

Output:

List of Tuples: [(1, 2, 3), ('S', 'P', 'Q')]

Python list of tuples using zip() function

Python zip() function can be used to map the lists altogether to create a list of tuples using the below command:

list(zip(list))

The zip() function returns an iterable of tuples based upon the values passed to it. And, further, the list() function would create a list of those tuples as an output from the zip() function.

Example:

lst1 = [10,20,30] lst2 = [50,"Python","JournalDev"] lst_tuple = list(zip(lst1,lst2)) print(lst_tuple)

Output:

[(10, 50), (20, 'Python'), (30, 'JournalDev')]

Customized grouping of elements while forming a list of tuples

While forming a list of tuples, it is possible for us to provide customized grouping of elements depending on the number of elements in the list/tuple.

[element for element in zip(*[iter(list)]*number)]

List comprehension along with zip() function is used to convert the tuples to list and create a list of tuples. Python iter() function is used to iterate an element of an object at a time. The ‘number‘ would specify the number of elements to be clubbed into a single tuple to form a list.

Example 1:

lst = [50,"Python","JournalDev",100] lst_tuple = [x for x in zip(*[iter(lst)])] print(lst_tuple)

In the above example, we have formed a list of tuples with a single element inside a tuple using the iter() method.

Output:

[(50,), ('Python',), ('JournalDev',), (100,)]

Example 2:

lst = [50,"Python","JournalDev",100] lst_tuple = [x for x in zip(*[iter(lst)]*2)] print(lst_tuple)

In this example, two elements are contained inside a tuple to form a list of tuple.

Output:

[(50, 'Python'), ('JournalDev', 100)]

Python list of tuples using map() function

Python map function can be used to create a list of tuples. The map() function maps and applies a function to an iterable passed to the function.

map(function, iterable)

Example:

lst = [[50],["Python"],["JournalDev"],[100]] lst_tuple =list(map(tuple, lst)) print(lst_tuple)

In this example, we have mapped the input list to the tuple function using map() function. After this, the list() function is used to create a list of the mapped tuple values.

Output:

[(50,), ('Python',), ('JournalDev',), (100,)]

Python list of tuples using list comprehension and tuple() method

Python tuple() method along with List Comprehension can be used to form a list of tuples.

The tuple() function helps to create tuples from the set of elements passed to it.

Example:

lst = [[50],["Python"],["JournalDev"],[100]] lst_tuple =[tuple(ele) for ele in lst] print(lst_tuple)

Output:

[(50,), ('Python',), ('JournalDev',), (100,)]

Python - Access Tuple Items

❮ Previous Next ❯

Access Tuple Items

You can access tuple items by referring to the index number, inside square brackets:

Example

Print the second item in the tuple:

thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Try it Yourself »

Note: The first item has index 0.

Python - Tuples

Advertisements

Previous Page
Next Page

A tuple is a collection of objects which ordered and immutable. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets.

Creating a tuple is as simple as putting different comma-separated values. Optionally you can put these comma-separated values between parentheses also. For example −

tup1 = ('physics', 'chemistry', 1997, 2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a", "b", "c", "d";

The empty tuple is written as two parentheses containing nothing −

tup1 = ();

To write a tuple containing a single value you have to include a comma, even though there is only one value −

tup1 = (50,);

Like string indices, tuple indices start at 0, and they can be sliced, concatenated, and so on.

Accessing nth element from Python tuples in list

PythonServer Side ProgrammingProgramming

A python list can contain tuples as its elements. In this article we will explore how to access every nth element form the tuples that are present as the elements in the given tuple.

Video liên quan

Postingan terbaru

LIHAT SEMUA