1

I have a list of tuples called list_cs:

('2015-05-14', 685)
('2015-04-15', 680)
('2015-03-20', 675)
('2015-02-11', 680)
('2015-01-13', 685)
('2014-12-10', 685)
('2014-11-25', 685)
('2014-10-09', 685)
('2014-09-15', 690)
('2014-08-21', 680)
('2014-07-22', 680)

For the first 5 tuples, I want to assign the scores in the second position of the tuple to unique variables. I do it like this:

cs0 = [x[1] for x in list_cs[0:1]]
cs1 = [x[1] for x in list_cs[1:2]]
cs2 = [x[1] for x in list_cs[2:3]]
cs3 = [x[1] for x in list_cs[3:4]]
cs4 = [x[1] for x in list_cs[4:5]]

I also want to assign the score in the second position of the last tuple to a unique variable. I never know how long the list might be; but I just want the last one. But, I can't figure out how to get that last one.

I've tried some of the following but none of them work.

cs1st = [x[1] for x in list_cs[-1:-0]]
cs1st = [x[1] for x in list_cs[-0:-1]]
cs1st = [x[1] for x in list_cs[:-1]]
cs1st = [x[1] for x in list_cs[-1]]

How can I do this?

UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
Jeff F
  • 975
  • 4
  • 14
  • 24
  • 3
    Why would you want to have distinct variables for these things? That's what things like lists and tuples are for! – Scott Hunter Jun 02 '15 at 20:08
  • Why do you need a list comprehension? Would `cs1st = list_cs[-1][1]` work? – Bonsaigin Jun 02 '15 at 20:11
  • I want to compare, for example, the first score with the third score or the fifth score with the second score and the last score with the first score. I'm not that good at coding so it's easier for me to just do it like, "if cs2 > cs0", do whatever. I'm sure there's a better way; just don't know it. – Jeff F Jun 02 '15 at 20:11
  • possible duplicate of [How can you dynamically create variables in Python via a while loop?](http://stackoverflow.com/questions/5036700/how-can-you-dynamically-create-variables-in-python-via-a-while-loop) – emvee Jun 02 '15 at 20:13

1 Answers1

2

You don't need a list comprehension to fetch one item.

cs0 = list_cs[0][1]
cs1 = list_cs[1][1]
…

Or, to generalize,

cs0, cs1, cs2, cs3, cs4 = [list_cs[i][1] for i in range(5)]

To get the last score:

cs1st = list_cs[-1][1]
200_success
  • 7,286
  • 1
  • 43
  • 74