Skip to content

Python get first element of tuple | Example code

  • by

You can access Python tuples with indexes. The index of the first element is 0 and the last element has an index of n-1.

Tuple First element:-

tuple[0]

Example get the first element of the tuple

Simple example code.

tup = (1, 2, 3, 4, 5)
print(tup[0])

Output:

Python get first element of tuple

Python gets the first elements from a tuple of strings

t = ("aaa", "aab", "abc", "aba", "bcc")
print(t[0])

Output: aaa

How to get the first element of each tuple in a list in Python?

Answer: Here is how to get the first element of each tuple in a list in Python

Use a list comprehension:

list_tuple = [(1, 2), ("A", "B"), (10, 20), ("elt1", "elt2")]

res_list = [x[0] for x in list_tuple]
print(res_list)

Output: [1, ‘A’, 10, ‘elt1’]

Another example code

rows = [(1, 2), (3, 4), (5, 6)]

res_list = [x[0] for x in rows]
print(res_list)

Output: [1, 3, 5]

Use indexing to get the first element of each tuple

Use a for-loop to iterate through a list of tuples. Within the for-loop, use the indexing tuple[0] to access the first element of each tuple, and append it.

tuple_list = [("a", "b"), ("c", "d")]

ele = []

for x in tuple_list:
    ele.append(x[0])

print(ele)

Output: [‘a’, ‘c’]

Do comment if you have any doubts and suggestions on this Python list code.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *