yatu
yatu

Reputation: 88236

List of words and letters to list of letters

I have a list which has strings of length 1 up to n:

a = ['a','aq','thw','z']

I'm trying to obtain a flat list with only length 1 elements, expanding those the length of which is greater than 1. My current solution is:

l = []
for i in a:
    l = l + list(i)
print(l)
['a', 'a', 'q', 't', 'h', 'w', 'z']

Is there a more straight forward way of doing this avoiding a for loop?

My impression is that there might not be, however I'm curious where as to know if there is some other more efficient perhaps built-in method to accomplish this. Thanks in advance.

Upvotes: 2

Views: 70

Answers (2)

cs95
cs95

Reputation: 402593

This is the easiest way I can think to do it, with str.join + listification.

>>> list(''.join(a))
['a', 'a', 'q', 't', 'h', 'w', 'z']

There's also the solution with chain:

>>> from itertools import chain
>>> list(chain.from_iterable(a)) # Thanks, @Patrick Haugh!
['a', 'a', 'q', 't', 'h', 'w', 'z']

They're all pretty fast.

a2 = a * 100000
%timeit list(''.join(a2))
%timeit list(chain.from_iterable(a2))
%timeit [letter for word in a2 for letter in word]

11.1 ms ± 247 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
32.3 ms ± 863 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
50.2 ms ± 1.3 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Upvotes: 6

Martin Frodl
Martin Frodl

Reputation: 657

Use a list comprehension:

>>> [letter for word in a for letter in word]
['a', 'a', 'q', 't', 'h', 'w', 'z']

Upvotes: 2

Related Questions