If you have only a nested list, not a deep nested list, you can use
If you always want to have a list as result, you can make a function for it.
Do you like it? You should read the whole description of this module. It's very powerful. Mostly all parts of Python language have implemented iteration. The benefit is also, that you can work with "big data" or data-streams. The iterator protocol allows this. The function
In addition, you get back, what you want. If you want to have a
This can be done also with
Bonus: You can do it also with
itertools.chain.from_iterable
from itertools import chain flatten = chain.from_iterable nested = [('a', 'b', 'r', 'a'),('c', 'a', 'd', 'a', 'b', 'r', 'a')] result = list(flatten(nested)) print(result)
Output:['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a']
chain.from_iterable returns an iterator. You have to consume this iterator to result by result.If you always want to have a list as result, you can make a function for it.
from itertools import chain def flatten_to_list(iterable): return list(chain.from_iterable(iterable)) nested = [('a', 'b', 'r', 'a'),('c', 'a', 'd', 'a', 'b', 'r', 'a')] print(flatten_to_list(nested))
Output:['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a']
Reference from Python documentation: itertools itertools-recipesDo you like it? You should read the whole description of this module. It's very powerful. Mostly all parts of Python language have implemented iteration. The benefit is also, that you can work with "big data" or data-streams. The iterator protocol allows this. The function
flatten_to_list
removes this ability, because the list is constructed in memory until the iteration ends. It's not possible with infinite streams, except if you use itertools.islice(iterable, start, end)
.In addition, you get back, what you want. If you want to have a
set
, then use set(chain.from_iterable(nested_something))
.This can be done also with
tuple
, list
, dict.fromkeys
and other types which consumes iterables.Bonus: You can do it also with
str.join
result1 = str.join('-', flatten(nested)) # or result2 = '-'.join(flatten(nested)) print(result1) print(result2)
Output:a-b-r-a-c-a-d-a-b-r-a
a-b-r-a-c-a-d-a-b-r-a
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!