views:

141

answers:

6

I'm just starting with programming. I have a list of a few strings and now I need to print the biggest (in length) one. So I first want to just print the lengths of elements. I was trying things like this:

l = ("xxxxxxxxx", "yyyy","zz")

for i in range(len(l):

So how do I do it?

+2  A: 

To print the lengths of the elements:

elements = ["xxxxxx", "yyy", "z"]
for element in elements:
    print len(element)

I recommend you read some tutorial material, for instance http://docs.python.org/tutorial/

codeape
The question asks to print the largest string.
Amit
@Amit: The question states "So I first want to just print the lengths of elements."
Greg Hewgill
A: 

The following code will print the largest string in the set:

l = ["abcdev", "xx","abcedeerer"]
len_0 = len(l[0])
pos = 0

for i in range(0,len(l)):
        if len(l[i]) > len_0:
                pos = i
print l[pos]
Amit
Why the -1? I gave the answer to "now I need to print the biggest (in length) one".. .
Amit
While I'm sure your solution works, it is not a good example on how to write Python code. To someone asking for help about Python, it's simply not helpful.
truppo
I probably wrote C there. Do you recommend using more Python constructs, like 'max...key' ?
Amit
+1  A: 

just ask for the max according to the length

print max(["qsf","qsqsdqsd","qs"], key = len)

chub
While that works, it's a bit subtle for a beginner.
Greg Hewgill
+7  A: 
l = ("xxxxxxxxx", "yyyy","zz")
print(max(l, key=len))

First of all you don't have a list, you have a tuple. this code will work for any sequence, however; both lists and tuples are sequences (as well as strings, sets, etc). So, the max function takes a key argument, that is used to sort the elements of an iterable. So, from all elements of l will be selected the one having the maximum length.

SilentGhost
+1  A: 
>>> sorted(['longest','long','longer'],key=len)[-1]
'longest'

UPDATE: SilentGhost's solution is a lot nicer.

Kalmi
A: 

thanks guys for all the great solutions. And sorry for the confusion about lists and tuples.

S7nf
SO is not a forum. Answers are supposed be answers to the question. Please consider marking one of the answers as a solution.
Kalmi