When it is required to find the character position of ‘K’th word from a list of strings, a list comprehension along with enumerate is used.
Below is a demonstration of the same −
my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) K = 15 print("The value of K is :") print(K) my_result = [element for sub in enumerate(my_list) for element in enumerate(sub)] my_result = my_result[K] print("The result is :") print(my_result)
The list is : ['python', 'is', 'fun', 'to', 'learn'] The value of K is : 15 The result is : 2
A list of strings is defined and is displayed on the console.
A value for ‘K’ is defined and is displayed on the console.
A list comprehension is used to iterate over the elements of the list using enumerate.
The zeroth element in every element is accessed using enumerate
This is converted to a list.
Since enumerate is used, the output would be an integer here.
The ‘K’th element of this list is displayed as the output on the console.