Reputation: 2900
Let's say we have a list such as:
g = ["123456789123456789123456",
"1234567894678945678978998879879898798797",
"6546546564656565656565655656565655656"]
I need the first twelve chars of each element :
["123456789123",
"123456789467",
"654654656465"]
Okay, I can build a second list in a for loop, something like this:
g2 = []
for elem in g:
g2.append(elem[:12])
but I'm pretty sure there are much better ways and can't figure them out for now. Any ideas?
Upvotes: 13
Views: 12269
Reputation: 318808
Use a list comprehension:
g2 = [elem[:12] for elem in g]
If you prefer to edit g
in-place, use the slice assignment syntax with a generator expression:
g[:] = (elem[:12] for elem in g)
Demo:
>>> g = ['abc', 'defg', 'lolololol']
>>> g[:] = (elem[:2] for elem in g)
>>> g
['ab', 'de', 'lo']
Upvotes: 20