Python – Extract element from a list succeeded by K

PythonServer Side ProgrammingProgramming

When it is required to extract element from a list succeeded by ‘K’, a simple iteration and the ‘append’ method is used.

Example

Below is a demonstration of the same

my_list = [45, 65, 32, 78, 99, 10, 21, 2]

print("The list is : ")
print(my_list)

K = 99
print("The value of K is ")
print(K)

my_result = []

for elem in range(len(my_list) - 1):
   if my_list[elem + 1] == K:
      my_result.append(my_list[elem])

print("The result is : " )
print(my_result)

Output

The list is :
[45, 65, 32, 78, 99, 10, 21, 2]
The value of K is
99
The result is :
[78]

Explanation

  • A list is defined and is displayed on the console.

  • The value for ‘K’ is defined and is displayed on the console.

  • An empty list is defined.

  • The list is iterated over and every element is checked to be equivalent to ‘K’.

  • If so, it is appended to the empty list using the ‘append’ method.

  • This list is displayed as the output on the console.

raja
Published on 20-Sep-2021 08:17:43
Advertisements