Python Sort List
Python Program to Sort the List According to the Length of the Words
Hey There Python Geeks,
In this python tutorial, I have shown how to sort the list according to the length of the words.
Consider a python list : list =['bye bye bye','hi','good morning','YouTube']
Take an empty list : empty_list = [ ]
Take another empty list : final_list = [ ]
Now, we need to find the length of the words which are there in the list and that can be done as : for i in list:
For every word in the list, we need to add the length of the words to the empty_list : empty_list.append(len(i))
We have every word length in empty_list,we need sort the empty_list ,so that we can have the words in order of low to high : empty_list.sort()
Take for loop for every element in empty_list and another for loop for every element in list : for i in empty_list:
for j in range(len(list)):
Now check if the length of element which is in list matches which the number in empty_list, if yes then add it to final_list :
if i == len(list[j])
final_list.append(list[j])
Now print the final_list to get the desired result : print(final_list)
The python code can be written as :
list =['bye bye bye','hi','good morning','YouTube']
empty_list = [ ]
final_list = [ ]
for i in list:
empty_list.append(len(i))
empty_list.sort()
for i in empty_list:
for j in range(len(list)):
if i == len(list[j])
final_list.append(list[j])
print(final_list)
In this python tutorial, I have shown how to sort the list according to the length of the words.
Consider a python list : list =['bye bye bye','hi','good morning','YouTube']
Take an empty list : empty_list = [ ]
Take another empty list : final_list = [ ]
Now, we need to find the length of the words which are there in the list and that can be done as : for i in list:
For every word in the list, we need to add the length of the words to the empty_list : empty_list.append(len(i))
We have every word length in empty_list,we need sort the empty_list ,so that we can have the words in order of low to high : empty_list.sort()
Take for loop for every element in empty_list and another for loop for every element in list : for i in empty_list:
Now check if the length of element which is in list matches which the number in empty_list, if yes then add it to final_list :
if i == len(list[j])
final_list.append(list[j])
Now print the final_list to get the desired result : print(final_list)
The python code can be written as :
list =['bye bye bye','hi','good morning','YouTube']
empty_list = [ ]
final_list = [ ]
for i in list:
empty_list.append(len(i))
empty_list.sort()
for i in empty_list:
for j in range(len(list)):
if i == len(list[j])
final_list.append(list[j])
print(final_list)
Comments
Post a Comment