Python's most efficient way to choose longest string in list?
From the Python documentation itself, you can use max
:
>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456
Longest string from a tuple in a list
You can use a dictionary (defaultdict
) to keep track of the longest message per ID:
from collections import defaultdict
# input
l = [("Hello world","1"), ("Helloworld","2"),("Hi, Hello world","1"),("How are you","3"),("HiHelloworld","2")]
d = defaultdict(lambda:('', float('-inf')))
for msg, ID in l:
if len(msg) > len(d[ID][0]):
d[ID] = (msg, ID)
out = list(d.values())
output:
[('Hi, Hello world', '1'), ('HiHelloworld', '2'), ('How are you', '3')]
Get the longest string from the list using python
You can fin the longest and the shortest strings in the list the following way:
a_list = ['abc', 'bcd', 'bcdefg', 'abba', 'cddc', 'opq']
# we give the both variable the value of the first element in the list
shortest = a_list[0]
longest = a_list[0]
for i in a_list[1:]:
if len(shortest) >= len(i): # check if current string in shorter
shortest = i # if yes change variable value
if len(longest) <= len(i): # check if current string in longer
longest = i # if yes change variable value
# print results:
print(shortest)
print(longest)
Most Pythonic and efficient to join list of strings until the length gets too high
products = ["Apple", "Banana", "Cherry", "Durian"]
string = products[0]
for v in products[1:]:
if len(string) + len(', ') + len(v) <= 20:
string = string + ', ' + v
else:
string = string + '...'
break
print(string)
Output:
Apple, Banana...
How to find the longest string in a list of lists of strings?
The following code will give you the length of the largest string -- whether or not it is inside a subset.
entries = [["this is text", "more text"], "another string"]
length = 0
for i in entries:
if type(i) is list:
value = len(max(i, key=len))
if length < value:
length = value
else:
value = len(i)
if length < value:
length = value
print(len("this is text"), len("more text"), len("another string"))
print(length)
Outputs:
12 9 14
14
Longest strings from list
First, we can find the maximum length of any string in the list:
stringlist = ['hi', 'hello', 'hey','ohman', 'yoloo', 'hello']
#maxlength = max([len(s) for s in stringlist])
maxlength = max(len(s) for s in stringlist) # omitting the brackets causes max
# to operate on an iterable, instead
# of first constructing a full list
# in memory, which is more efficient
A little explanation. This is called a list comprehension, which allows you to comprehend one list as another list. The code [len(s) for s in stringlist]
means "generate a list-like object, by taking stringlist
, and for every s
in that list, give me instead, len(s)
(the length of that string).
So now we have a list [2, 5, 3, 5, 5, 5]
. Then we call the built-in max()
function on that, which will return 5
.
Now that you have the max length, you can filter the original list:
longest_strings = [s for s in stringlist if len(s) == maxlength]
This does just as it reads in english: "For each string s
in stringlist, give me that string s
, if len(s)
is equal to maxlength
."
Finally, if you want to make the result unique, you can use the set()
constuctor to generate a unique set:
unique_longest_strings = list(set(longest_strings))
(We are calling list()
to turn it back into a list after removing the duplicates.)
This boils down to:
ml = max(len(s) for s in stringlist)
result = list(set(s for s in stringlist if len(s) == ml))
Note: Don't use a variable named list
, as it overrides the meaning of the name for the list
type.
print the length of the longest string in the list
names = ['ron', 'james', 'kevin07']
best = 0
for index in range(len(names)):
if len(names[index]) > best:
best = len(names[index])
print(best)
Output:
7
Explanation:
You need to move the print(best) outside of loop
Related Topics
Typeerror: Unhashable Type: 'Dict'
How to Construct a Timedelta Object from a Simple String
How to Get the Input from the Tkinter Text Widget
How to Remove Non-Ascii Characters But Leave Periods and Spaces
Python: Access Class Property from String
Opencv Giving Wrong Color to Colored Images on Loading
What Is the Fastest Way to Flatten Arbitrarily Nested Lists in Python
Why Is Tkinter Entry's Get Function Returning Nothing
How to Read a File with a Semi Colon Separator in Pandas
Automatically Create Requirements.Txt
Compare Two Dataframes and Output Their Differences Side-By-Side
Python Setup.Py Develop VS Install
What Is the Purpose of Class Methods