
- 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
List expansion by K in Python
In this article, we are going to learn how to expand the list by replicating the element K times. We'll two different ways to solve the problem.
Follow the below steps to solve the problem.
- Initialize the list, K, and an empty list.
- 3Iterate over the list and add current element K times using replication operator.
- Print the result.
Example
Let's see the code.
# initializing the list numbers = [1, 2, 3] K = 5 # empty list result = [] # expanding the list for i in numbers: result += [i] * K # printing the list print(result)
If you run the above code, then you will get the following result.
Output
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Follow the below steps to solve the problem.
- Initialize the list and K.
- Iterate over the list and add current element K times using an inner loop.
- Print the result.
Example
Let's see the code.
# initializing the list numbers = [1, 2, 3] K = 5 # expanding the list result = [i for i in numbers for j in range(K)] # printing the list print(result)
If you run the above code, then you will get the following result.
Output
[1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Conclusion
If you have any queries in the article, mention them in the comment section.
- Related Articles
- Python – Sort String list by K character frequency
- Python – Extract element from a list succeeded by K
- Program to reverse linked list by groups of size k in Python
- Rotate List Left by K in C++
- Python – Maximum of K element in other list
- Program to check we can reach end of list by starting from k in Python
- Find k longest words in given list in Python
- Python – Trim tuples by K
- Smallest Integer Divisible by K in Python
- Python - Number of values greater than K in list
- Find minimum k records from tuple list in Python
- Python – Sort row by K multiples
- Program to rotate a linked list by k places in C++
- Unix style pathname pattern expansion in Python (glob)
- Python - Sort rows by Frequency of K

Advertisements