Issue
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?
Solution
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.
Answered By - Dan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.