This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
How do I make a flat list out of a list of lists?
(34 answers)
Closed 1 year ago.
How can I flatten a list of lists into a list?
For ex,:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Expectation:
Final_List = ['a','b','c','d','e','f']
You will need to check the type of each list item to determine if it is merely a value to output or a sublist to expand.
Using a list comprehension:
Input_List = [['a', 'b'],'c','d',['e', 'f']]
Final_List = [v for i in Input_List for v in (i if isinstance(i,list) else [i])]
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using an iterative loop:
Final_List = []
for item in Input_List:
if isinstance(item,list): Final_List.extend(item)
else: Final_List.append(item)
print(Final_List)
['a', 'b', 'c', 'd', 'e', 'f']
Or using a recursive function if you need to flatten all levels of nested lists:
def flat(A):
return [v for i in A for v in flat(i)] if isinstance(A,list) else [A]
Input_List = [['a', 'b'],'c','d',['e2', 'f3',['x','y']]]
Final_List = flat(Input_List)
print(Final_List)
['a', 'b', 'c', 'd', 'e2', 'f3', 'x', 'y']
this working only for -> multdimensional at the same dimension
from itertools import chain
ini_list = [[1, 2, 3],
[3, 6, 7],
[7, 5, 4]]
print ("initial list ", str(ini_list))
flatten_list = list(chain.from_iterable(ini_list))
print ("final_result", str(flatten_list))
If some arrays isn't nested - then
def flatten(something):
if isinstance(something, (list, tuple, set, range)):
for sub in something:
yield from flatten(sub)
else:
yield something
test = flatten(ini_list)
list(test)
Related
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 6 months ago.
I have a list with the following structure:
list = ['a', ['b','c','d'], ['e','f']]
how can I create the following structure from it:
list = ['a','b','c','d','e','f']
list = ['a', ['b','c','d'], ['e','f']]
lst = [element for nested_list in list for element in nested_list]
print(lst)
Result:
['a', 'b', 'c', 'd', 'e', 'f']
This supports nested list too.
res = []
def parse(li):
if isinstance(li, list):
for a in li:
parse(a)
return
res.append(li)
my_List = ['a', ['b','c','d', ['g', 'h']], ['e','f']]
parse(my_List)
print(res)
Output:
['a', 'b', 'c', 'd', 'g', 'h', 'e', 'f']
This question already has answers here:
Checking if a list has duplicate lists
(7 answers)
Closed 3 years ago.
I have the following list:
L = [['a', 'b'], ['x'], ['a', 'b', 'c'], ['a', 'b']]
I want to check whether there are duplicates in the list.
Have tried:
def checkIfDuplicates_(listOfElems):
''' Check if given list contains any duplicates '''
for elem in listOfElems:
if listOfElems.count(elem) > 1:
return True
return False
and
len(L)==len(set(L))
and turn each sublist into tuples
check_L = list(set(tuple(L) for x in L))
Not working
You were actually really close with this:
check_L = list(set(tuple(L) for x in L))
There is a minor mistake, in that you are using tuple(L) where you actually want tuple(x). If we correct that, we get:
>>> list(set(tuple(x) for x in L))
[('a', 'b', 'c'), ('x',), ('a', 'b')]
And to turn back into a nested list, we can do this:
>>> [list(y) for y in set(tuple(x) for x in L)]
[['a', 'b', 'c'], ['x'], ['a', 'b']]
Hope that helps!
Basically what I am trying is seeing if I can flatten down nested lists when the list contains 1 single item which is another list. For example take this data structure:
[['a', 'b', 'c', [['d', 'e', 'f']]]]
The ideal format of the data would be:
['a', 'b', 'c', ['d', 'e', 'f']]
This nesting can go any amount of levels deep but just need to flatten out single list data. Anyone know a way of doing this? The closest I got with answers on SO was: Flattening a list recursively But this completely flattens the list as a whole.
You can use a recursive function that specifically tests if there's only one item in the given list and if that one item is a list, and if so, skips yielding that list:
def simplify(l):
if len(l) == 1 and isinstance(l[0], list):
yield from simplify(l[0])
else:
for i in l:
yield list(simplify(i)) if isinstance(i, list) else i
so that:
list(simplify([['a', 'b', 'c', [['d', 'e', 'f']]]]))
returns:
['a', 'b', 'c', ['d', 'e', 'f']]
A recursive function can do this:
def flatten(l: list):
if len(l) == 1:
if isinstance(l[0], list):
l = l[0]
for i, elem in enumerate(l):
if isinstance(type(elem), list):
l[i] = flatten(elem)
return l
This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 4 years ago.
I do not have much experience in Python.
All I want to do is to insert elements in nested lists.I have two lists which seems to be similar but their behaviour is completely different.
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
When I output print these two lists both give same output:
[['a', 'b'], ['a', 'b'], ['a', 'b']]
But when I try to insert elements in nested lists both do that in a different way. Below is the code for inserting elements in nested list.
list1 = [['a','b']] * 3
for item in list1:
item.append("Hello")
print (list1)
This outputs
[['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello'], ['a', 'b', 'Hello', 'Hello', 'Hello']]
While when I define list in the following way it does exactly what I want.
list2 = [['a','b'],['a','b'],['a','b']]
for item in list2:
item.append("Hello")
print (list2)
This gives following output:
[['a', 'b', 'Hello'], ['a', 'b', 'Hello'], ['a', 'b', 'Hello']].
Why are these two behaving differently?
list1 = [['a','b']] * 3
list2 = [['a','b'],['a','b'],['a','b']]
Screenshot of Program output
list1 = [['a', 'b']] * 3
This creates a list of lists, as you know. However, the nested lists are actually all references to the same list object.
So when you iterate over list1 with
for item in list1:
item refers to the same list object on each iteration. So you repeated append to the same list.
On the other hand, list2 in your example code is explicitly assigned a list with three different lists. Those lists happen to have the same elements, but they are distinct lists.
When you use the * operator here, you are saying "I want 3 of these".
So you're getting 3 references to the same ['a', 'b']. In your case, you're adding 'Hello' to that same ['a', 'b'] reference.
List of lists changes reflected across sublists unexpectedly
If you want to make 3 separate references, try using list comprehension:
>>> x = [['a', 'b'] for i in range(0, 3)]
>>> x
[['a', 'b'], ['a', 'b'], ['a', 'b']]
>>> x[0].append('Hello')
>>> x
[['a', 'b', 'Hello'], ['a', 'b'], ['a', 'b']]
This question already has answers here:
How to get the cartesian product of multiple lists
(17 answers)
Closed 5 years ago.
Suppose there are two lists:
['a', 'b', 'c'], ['d', 'e', 'f']
what I want is:
'ad','ae','af','bd','be','bf','cd','ce','cf'
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)
my question is if there are not only two lists, how to improve the code?
for example,
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
print ['adg','adh','adq','aeg','aeh',.......]
guys,are there any generalizable ways to show n lists..I mean what if there are more than three lists?
This is called a cartesian product.
import itertools
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
lists = [first_list, second_list, third_list]
cartesian_product = [''.join(x) for x in itertools.product(*lists)]
print(cartesian_product)
Output:
['adg', 'adh', 'adq', 'aeg', 'aeh', 'aeq', 'afg', 'afh', 'afq',
'bdg', 'bdh', 'bdq', 'beg', 'beh', 'beq', 'bfg', 'bfh', 'bfq',
'cdg', 'cdh', 'cdq', 'ceg', 'ceh', 'ceq', 'cfg', 'cfh', 'cfq']
You can try it online, here.
Here's an example implementation of a cartesian production function, which you can try out here.
def cartesian_product(*lists):
if not lists: # base case
return [[]]
else:
this_list = lists[0]
remaining_lists = lists[1:]
return [
[x] + p
for x in this_list
for p in cartesian_product(*remaining_lists)
]
I haven't tested this but this should work.
first_list = ['a', 'b', 'c']
second_list = ['d', 'e', 'f']
third_list = ['g','h','q']
combined_list = []
for i in first_list:
for j in second_list:
for k in third_list:
combined_list.append(i + j + k)
print(combined_list)