Home > Software design >  Why can I not extract the values I want from my tuple list?
Why can I not extract the values I want from my tuple list?

Time:03-22

I have a list of tuples with each item in the list having 4 values within them. I am trying to create a new list by taking the last value in each of these tuples. For example I want to take the 1's and the 4's which can be seen in each of the tuples in the list and create a list which would read [1,1,1,1,1,4,4,4,4,4]. The list is as follows:

values = [(7.4, 2.4, 2.2, 1),
          (7.4, 4.9, 4.3, 1),
          (7.3, 2.3, 4.4, 1),
          (7.4, 2.4, 4.4, 1),
          (8.2, 2.4, 4.2, 1),
          (8.6, 2.3, 4.4, 4),
          (7.4, 3.5, 4.2, 4),
          (7.6, 3.9, 4.2, 4),
          (6.9, 2.6, 4.6, 4),
          (8.1, 3.9, 4.3, 4)]

I have been seriously struggling with this as I am very new to Python and I have attempted lots of research but cannot make sense of any of it.

So far I have tried to use newList = values [1:9][3] which simply returned (8.2, 2.4, 4.2, 1) which I am aware I am identifying with the code. I have tried many other things and the closest I've got is to identify just the 4th value (i.e. 4 or 1) of one tuple. I am unsure of how I can create a new list of all 10 4th values. Am I oversimplifying it? Does it need a few lines more code? Any help would be amazing!

CodePudding user response:

Use list comprehension:

my_list = [x[3] for x in values]

Or use a simple for loop:

my_list = []
for x in values:
    my_list.append(x[3])
  • Related