How to extract data from a list of tuples which length could be variable

Viewed 364

I have a list which contains multiple tuples (the length of items is variable) and I want to extract some specific data located at the same rank inside the tuples.

Let me show you an example. Let's work on this list of 3 tuples:

x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

I want to retrieve the fourth items of each tuples. I use the length of the list within a While loop:

y = len(x)
while y > 0:
    print(x[0][3])
    y = y - 1

The result I get is:

d4
d4
d4

But I want the following result:

d4
h8
l12

Is there a way to replace the [0] by the y variable inside this section print(x[0][3]) to get the result I want?

6 Answers

It would be more natural to use a for loop for this:

for item in x:
    print(item[3])

The reason your code didn't work was because you had hard-coded it to always get the first tuple in your list i.e. in print(x[0][3]) the 0 in x[0] needed to be a variable that iterates through your list. This would be easier if you count up instead of down i.e.

counter = 0
while counter < len(x):
    print(x[counter][3])
    counter += 1

but it really doesn't make sense to use while for this when for exists.

Just simple iterate on them and once you done you will get the tuples only like the following

('a1', 'b2', 'c3', 'd4')
('e5', 'f6', 'g7', 'h8') 
('i9', 'j10', 'k11', 'l12')

and once you get them index on each tuple to get the last value like [-1] or [len(tuples) - 1] and the following are my codes


x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

read = [i[-1] for i in x]
print(read)

Try this one:

[each_tuple[-1] for each_tuple in x]

You can try this:-

y = len(x)
while y>0:
    print(x[len(x)-y][3])
    y = y-1

Output:-

d4
h8
l12

Try for loop

x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

for y in x:
    print(y[3])

While loop

c = len(x)-1
while c>=0:
    print(x[c][-1])
    c-=1
    
Related