Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add string to every element of a python list

I have a list made of a python dictionary keys via; list(dict.keys()).

dict.keys()
dict_keys(['South', 'North'])

I would like to add a string to the every element in the list = ['South', 'North'] like:

my_string = 'to_'

In the end I want to have list = ['to_South', 'to_North']

Is there a method I could use for this?

something like:

list.add_beginning_of_each_element('to_')
like image 379
oakca Avatar asked Dec 05 '18 12:12

oakca


3 Answers

Or map:

>>> l = ['South', 'North']
>>> list(map('to_'.__add__,l))
['to_South', 'to_North']
>>>

There a add_prefix in pandas, so if you have a pandas dataframe, you can just use add_prefix to add to the columns, an example of making a dataframe out of a list and having them as columns:

>>> import pandas as pd
>>> pd.DataFrame(columns=['South', 'North']).add_prefix('to_').columns.tolist()
['to_South', 'to_North']
like image 108
U12-Forward Avatar answered Jan 07 '23 12:01

U12-Forward


Use a list comprehension:

lst = ['South', 'North']
result = ['to_' + direction for direction in lst]

As an alternative you could use map:

def add_to_beginning(s, start='to_'):
    return start + s

lst = ['South', 'North']

result = list(map(add_to_beginning, lst))
print(result)
like image 35
Dani Mesejo Avatar answered Jan 07 '23 14:01

Dani Mesejo


You can use lambda function:

lst = ['South', 'North']
result = list(map(lambda x: 'to_' + x, lst))
like image 21
Manualmsdos Avatar answered Jan 07 '23 12:01

Manualmsdos