
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Extract tuples having K digit elements in Python
- Python – Average of digit greater than K
- Python – K middle elements
- Python – Split Numeric String into K digit integers
- Python program to extract Mono-digit elements
- Women, Caste and Reform
- Top K Frequent Elements in Python
- Python Program for Smallest K digit number divisible by X
- Python – Next N elements from K value
- Python – Random insertion of elements K times
- Python – Sort by a particular digit count in elements
- Program to find k where k elements have value at least k in Python
- Delete elements with frequency atmost K in Python
- Python – Remove Elements in K distance with N
- Python – Elements with factors count less than K

Advertisements