I'm looking for a "for loop" that finds the length of each item and choose the largest number.
>>>T=[chicken, soda, candy]
>>>Highest = 0
>>>"for loop goes here"
>>>print (highest)
7
I'm looking for a "for loop" that finds the length of each item and choose the largest number.
>>>T=[chicken, soda, candy]
>>>Highest = 0
>>>"for loop goes here"
>>>print (highest)
7
You need quotes around your strings (e.g. "chicken"
), and the case of variables matters so Highest
and highest
are different. Also use round parentheses ()
for a tuple and square []
for a list.
A simple way to do this in Python is be to use max()
to find the longest string, and len()
to find the lengths, with the for
keyword creating a generator expression:
T=("chicken", "soda", "candy")
Highest = max(len(x) for x in T)
print(Highest)
Slightly older versions of Python would use a list comprehension:
Highest = max([len(x) for x in T])
erip's answer showed how to use a for loop instead.
T is not a tuple, but a list. You can find out by doing print(type(T))
. Try to read up on lists and Python programming in general, there are quite a few good resources available. If you want T to be a Tuple, simply change the brackets []
to regular ()
parenthesis like this T = ("chicken", "soda", "candy")
, looping through it works the same way as mentioned below, so no need to change any of that.
The elements in your list T
needs to be some kind of type or variable. What you are looking for is probably a String. To create the words as the String type, put it in double quotes like this "chicken"
.
Heres what I suspect that you are looking for:
T = ["chicken", "soda" ,"candy"]
Highest = 0
for word in T:
lengthOfWord = len(word)
if lengthOfWord > Highest:
Highest = lengthOfWord
print(Highest)
You can also check out a live version here.
You can create list of lengths with the following:
[len(i) for i in T]
You can then call max
on an iterable, which will return the maximum element.
Putting this together you have:
print(max([len(i) for i in T]))
If you want a for-loop
explicitly, you can use this:
max_length = 0
for i in T:
max_length = max(len(i), max_length))
print(max_length)
Note these both work for list
s and tuple
s.