Accept a list of words and write a Python program to print words from list having 3 letters with index. Observe this example :

Python program to print words from list having 3 letters with index – Sample Output

Program Definition

Write a function ThreeLetters(L), where L is the list of elements (list of words) passed as an argument to the function. The function returns another list named ‘l3’ that stores all three letter words along with its index.

Accept a list L as a parameter and display it as follows:

If L contains [“RAJ”, “ANKIT”, “YUG”, “SHAAN”, “HET”]

The list l3 will have [“RAJ”,0,”YUG”,2,”HET”,4]

Steps

  1. Define a function ThreeLetters(L)
  2. Declare an empty list
  3. Traverse the list using for loop with range() function for index value
  4. Use if condition to get the words having 3 letters
  5. Append the value L[i] then index into L3
  6. Return L3
  7. Call the function with the appropriate input

Code

def ThreeLetters(L):
  l3=[]
  for i in range(len(L)):
    if len(L[i])==3:
      l3.append(L[i])
      l3.append(i)
  return l3

l=eval(input("Enter the list of words"))
print(ThreeLetters(l))

Output

Python program to print words from list having 3 letters with index

Follow this link for more Python programs:

Python Questions

Leave a Reply