By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,772 Members | 961 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,772 IT Pros & Developers. It's quick & easy.

How to access the middle value of a list separated by commas

P: n/a
[3,4,5]

and i want to assign these values to variables, but i want to assign the number with the middle VALUE, how do i go about doing that?
Oct 20 '10 #1
Share this Question
Share on Google+
8 Replies


Expert 100+
P: 621
See Section 1.1.5 at this onine book.
Oct 20 '10 #2

P: 3
that didn't really help :/... if i already assigned 2 of the numbers can i assign it by the only unassigned element in the list?
Oct 20 '10 #3

Expert 100+
P: 621
You should at least read it, before asking someone else to do it for you. Verbatim copy:
l = ['a', 'b', 1, 'a cat']
and access it with indices, exactly as you did with character strings:
>>> l[1]
'b'
Oct 20 '10 #4

P: 3
yes yes, i know that but the problem was that the list is user inputed and it is subject to change so that wont work and besides i read it all, it doesn't even cover all the function possibilities of a list.
Oct 20 '10 #5

Expert 100+
P: 391
Do you mean the median of the list? Eg if your list were [5,3,4] would you want to assign a variable to 4, or to 3? I think the question is ambiguous. Perhaps you can try to be more clear about exactly what it is that you want.

Is the issue that the list might have a variable number of elements? Or that you want to assign to the median element? Or that you want to assign to an element that has not yet been used for something?

Help us to help you!
Oct 25 '10 #6

P: 3
yes,It was a question about returning the median of a list of only 3 elements that the user enters, heres a snippet of my code if it helps, i need B to represent the median of the list.

[side_1=input('Enter side one: ')
side_2=input('Enter side two: ')
side_3=input('Enter side three: ')
values=[side_1,side_2,side_3]
A=min(values)
B=
C=max(values)]
Oct 25 '10 #7

bvdet
Expert Mod 2.5K+
P: 2,851
The median of any list is the middle value in a sorted list.
Expand|Select|Wrap|Line Numbers
  1. >>> values = [3,8,2,9,6]
  2. >>> sorted(values)
  3. [2, 3, 6, 8, 9]
  4. >>> sorted(values)[len(values)/2]
  5. 6
  6. >>> 
It's a bit more complicated when the list contains an even number of elements.
Oct 25 '10 #8

Expert 100+
P: 391
bvdet's method should work fine for you, Justin. Although, if you're using python 3, if I recall it won't do the floor division, so instead use:
Expand|Select|Wrap|Line Numbers
  1. B=sorted(values)[(len(values)-1)/2]
or, since you know the length already, just use:
Expand|Select|Wrap|Line Numbers
  1. B=sorted(values)[1]
Oct 26 '10 #9

Post your reply

Sign in to post your reply or Sign up for a free account.