Python – Get all numbers combinations in list
Last Updated :
14 Mar, 2023
Sometimes, while working with Python lists, we can have a problem in which we need to concatenate each number with other create new number. This kind of problem is peculiar but can have application in many domains such as day-day programming and gaming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [7, 3, 4, 5] Output : [73, 74, 75, 34, 35, 45] Input : test_list = [2, 5] Output : [25]
Method #1 : Using list comprehension + combination() The combination of above functions can be used to solve this problem. In this, we perform the task of finding all combination using combination() and f-strings can be used to perform concatenation.
Python3
from itertools import combinations
test_list = [ 59 , 236 , 31 , 38 , 23 ]
print ("The original list : " + str (test_list))
res = [ int (f"{x}{y}") for x, y in combinations(test_list, 2 )]
print (" All numbers combinations : " + str (res))
|
Output :
The original list : [59, 236, 31, 38, 23] All numbers combinations : [59236, 5931, 5938, 5923, 23631, 23638, 23623, 3138, 3123, 3823]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. list comprehension + combination() performs n number of operations.
Auxiliary Space: O(n), extra space is required where n is the number of elements in the list
Method #2 : Using loop + str() + int() The combination of above functions can be used to solve this problem. In this we perform the task of forming combinations using brute force and type conversions in nested loop. This also outputs reverse combinations.
Python3
from itertools import combinations
test_list = [ 59 , 236 , 31 , 38 , 23 ]
print ("The original list : " + str (test_list))
res = []
for i in test_list:
for j in test_list:
if j ! = i:
res.append( int ( str (i) + str (j)))
print (" All numbers combinations : " + str (res))
|
Output :
The original list : [59, 236, 31, 38, 23] All numbers combinations : [59236, 5931, 5938, 5923, 23659, 23631, 23638, 23623, 3159, 31236, 3138, 3123, 3859, 38236, 3831, 3823, 2359, 23236, 2331, 2338]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...