I've got a list ['a', 'b', 'c', 'd'] and I need a list ['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd'].
I've been looking at itertools, but I'm not seeing how to make this work.
For all combinations, the code would be:
from itertools import permutations
stuff = ['a','b','c','d']
for i in range(0, len(stuff)+1):
for subset in permutations(stuff, i):
print(subset)
What would I need to do to return only sequential combinations? I guess I could check the order for each permutation as I go, but that doesn't seem to be the best way.
Python comes with a direct function range() which creates a sequence of numbers from start to stop values and print each item in the sequence. We use range() with r1 and r2 and then convert the sequence into list.
chain() method is passed the arguments of list1, list2 and list3. This method takes multiple arguments and returns a single sequence of items. So, the chain() method concatenates all three lists. The result of the method call is converted into a list using the list() method.
Using the range() function to create a list from 1 to 100 in Python. In Python, we can use the range() function to create an iterator sequence between two endpoints. We can use this function to create a list from 1 to 100 in Python. The function accepts three parameters start , stop , and step .
Using + operator The + operator does a straight forward job of joining the lists together. We just apply the operator between the name of the lists and the final result is stored in the bigger list. The sequence of the elements in the lists are preserved.
Quite simply:
stuff = ['a','b','c','d']
print([''.join(stuff[i:j]) for i in range(len(stuff)) for j in range(i+1, len(stuff)+1)])
Gives
['a', 'ab', 'abc', 'abcd', 'b', 'bc', 'bcd', 'c', 'cd', 'd']
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