Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
How can I get this without recursion or list comprehension? I mean only use loops, using python?
The easiest way to combine Python lists is to use either list unpacking or the simple + operator. Let’s take a look at using the + operator first, since it’s syntactically much simpler and easier to understand. Let’s see how we can combine two lists: We can see here that when we print out third list that it combines the first and second.
Given a list, the task is to write a Python program to concatenate all elements in a list into a string. Input: ['hello', 'geek', 'have', 'a', 'geeky', 'day'] Output: hello geek have a geeky day Here, we are taking a list of words, and by using the Python loop we are iterating each element and concatenating words with the help of the “+” operator.
Python comes built-in with a helpful library called itertools, that provides helpful functions to work with iteratable objects. One of the many functions it comes with it the combinations () function. This, as the name implies, provides ways to generate combinations of lists. Let’s take a look at how the combinations () function works:
You learned how to do this with the itertools.combinations function and the `itertools.combinations_with_replacement_ function. The functions allow you to pass in a list and get the combinations without and with replacements, respectively. To learn more about the itertools.combinations function, check out the official documentation here.
The itertools
module implements a lot of loop-like things:
combined = []
for pair in itertools.product(['a', 'b', 'c'], ['d', 'e', 'f']):
combined.append(''.join(pair))
While iterating through the elements in the first array, you should iterate all of the elements in the second array and push the combined result into the new list.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
combined_list = []
for i in first_list:
for j in second_list:
combined_list.append(i + j)
print(combined_list)
This concept is called a Cartesian product, and the stdlib itertools.product
will build one for you - the only problem is it will give you tuples like ('a', 'd')
instead of strings, but you can just pass them through join for the result you want:
from itertools import product
print(*map(''.join, product (['a','b,'c'],['d','e','f']))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With