rmore911
rmore911

Reputation: 215

How to modify each element in a list without creating a new list

I want to modify all elements in a list such that I delete all characters after certain specific characters.

list is ['JACK\NAME1','TOM\NAME2'] and I want to modify it into ['JACK', 'TOM']

Right now I am using a For Loop with Split command:

text = ['JACK\\NAME1','TOM\\NAME2']

text_use = []

for item in text:
    item = item.split('\\',1)[0]
    text_use.append(item)

text_use

But I also have to create a new empty list (text_use) and append items to it. Is there a better way to do this? Where I don't have to use a For Loop?

Or where I don't have to create an empty list and then append items to it?

Thank you

R

Upvotes: 0

Views: 1400

Answers (3)

Francisco
Francisco

Reputation: 11486

In my opinion, it's more idiomatic (pythonic) to use enumerate:

for i, item in enumerate(text):
    text[i] = item.split('\\',1)[0]

Upvotes: 3

John Gordon
John Gordon

Reputation: 33335

Iterate over the list positions instead of the list values, and then access the items by their position in the list:

for pos in range(len(text)):
    text[pos] = text[pos].split('\\',1)[0]

Upvotes: 0

SuperStew
SuperStew

Reputation: 3054

like this

text = ['JACK\\NAME1','TOM\\NAME2']
text = [x.split('\\',1)[0] for x in text]

Upvotes: 0

Related Questions