Arvinth Kumar
Arvinth Kumar

Reputation: 1014

Need help for inserting values in between each value of a list

I am having a list column_names with below values

 column_names = ['Large Cap', 'Mid Cap', 'Small Cap', 'Value']

I need to create a list with below output. Duplicate values and append strings alternatively(_PE & _book) to values in list. Expected output:

column_names_PE =  ['Large Cap_PE', 'Large Cap_book','Mid Cap_PE','Mid Cap_book' 'Small Cap_PE', 'Small Cap_book' 'Value_PE','Value_book']

I can append strings using code [s + "_PE" for s in column_names]. But not sure how to duplicate and append strings alternatively. Can any one please help me.

Upvotes: 1

Views: 33

Answers (4)

Laurent LAPORTE
Laurent LAPORTE

Reputation: 22952

If you have:

column_names = ['Large Cap', 'Mid Cap', 'Small Cap', 'Value']
suffixes = ["_PE", "_book"]

To create the list with suffixes, you can do:

Using a classic loop:

column_names_PE = []
for column_name in column_names:
    for suffix in suffixes:
        column_names_PE.append(column_name + suffix)

Using a list in comprehension:

column_names_PE = [column_name + suffix
                   for column_name in column_names
                   for suffix in suffixes]

You get:

['Large Cap_PE',
 'Large Cap_book',
 'Mid Cap_PE',
 'Mid Cap_book',
 'Small Cap_PE',
 'Small Cap_book',
 'Value_PE',
 'Value_book']

Upvotes: 2

janos
janos

Reputation: 124646

A simple list-comprehension would get you a bit closer:

>>> [[c + '_PE', c + '_book'] for c in column_names]
[['Large Cap_PE', 'Large Cap_book'], ['Mid Cap_PE', 'Mid Cap_book'], ['Small Cap_PE', 'Small Cap_book'], ['Value_PE', 'Value_book']]

To flatten the nested list, you could use chain from itertools:

>>> from itertools import chain
>>> list(chain.from_iterable([[c + '_PE', c + '_book'] for c in column_names]))
['Large Cap_PE', 'Large Cap_book', 'Mid Cap_PE', 'Mid Cap_book', 'Small Cap_PE', 'Small Cap_book', 'Value_PE', 'Value_book']

Upvotes: 2

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You could just iterate through column_names and append a value for item + "_PE" and item + "_book":

column_names = ['Large Cap', 'Mid Cap', 'Small Cap', 'Value']

column_names_PE = []

for item in column_names:
  column_names_PE.append(item + "_PE")
  column_names_PE.append(item + "_book")

print(column_names_PE)
# ['Large Cap_PE', 'Large Cap_book', 'Mid Cap_PE', 'Mid Cap_book',
#  'Small Cap_PE', 'Small Cap_book', 'Value_PE', 'Value_book']

Upvotes: 2

whackamadoodle3000
whackamadoodle3000

Reputation: 6748

[item for sublist in [(s + "_PE",s + "_book") for s in column_names] for item in sublist]

You could try this list comprehension which appends a tuple and then flattens the list. Result:

['Large Cap_PE',
 'Large Cap_book',
 'Mid Cap_PE',
 'Mid Cap_book',
 'Small Cap_PE',
 'Small Cap_book',
 'Value_PE',
 'Value_book']

Upvotes: 1

Related Questions