Python – Reform K digit elements


When it is required to reform K digit elements, a list comprehension and the ‘append’ method are used.

Example

Below is a demonstration of the same

my_list = [231, 67, 232, 1, 238, 31, 793]

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

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

temp = ''.join([str(ele) for ele in my_list])

my_result = []

for index in range(0, len(temp), K):
   my_result.append(int(temp[index: index + K]))

print("The resultant list is :")
print(my_result)

Output

The list is :
[231, 67, 232, 1, 238, 31, 793]
The value of K is
3
The resultant list is :
[231, 672, 321, 238, 317, 93]

Explanation

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

  • The value for K is initialized and is displayed on the console.

  • A list comprehension is used to iterate over the elements in the list and convert it to a string type, and join it by spaces.

  • This is assigned to a variable.

  • An empty list is defined.

  • The value up to K is iterated over and the elements from index 0 to K is appended to the empty list.

  • This is the output which is displayed on the console.

Updated on: 14-Sep-2021

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements