2

I want to add 2 column constant to a list at the 1st column and the 2nd column.

I wrote 2 loop, because I wanted to add 2 columns.

I use this code:

list_a=[[1,'aa'],[2,'bb'],[3,'cc'],[4,'dd']]
constant1=2018
constant2=30
for item in list_a:
    item.insert(0,constant1)
for item in list_a:
    item.insert(1,constant2)
print(list_a)

The output is:

[[2018, 30, 1, 'aa'], [2018, 30, 2, 'bb'], [2018, 30, 3, 'cc'], [2018, 30, 4, 'dd']]

But I think this is not a good idea,is there any other way?

jpp
  • 159,742
  • 34
  • 281
  • 339

2 Answers2

2

You can use a list comprehension:

res = [[2018, 30, *v] for v in list_a]

[[2018, 30, 1, 'aa'],
 [2018, 30, 2, 'bb'],
 [2018, 30, 3, 'cc'],
 [2018, 30, 4, 'dd']]

Making operations "in place" has no significant advantage here. You have the same time complexity either way.

jpp
  • 159,742
  • 34
  • 281
  • 339
1

It is easy with pandas dataframe, if you are ok with creating a new list rather than changing it in place and do not mind installing an extra package. pandas is highly recommended if your work with large tables. For simplicity I assume columns are typed, which is the case in your example.

The code below is based on

how do I insert a column at a specific column index in pandas?

import pandas as pd

df = pd.DataFrame(list_a)
df.insert(0, "first", value=constant1)
df.insert(1, "second", value=constant2)

list_a = df.values.tolist()

back convertion to lists from dataframe is a bit slow because, probably because once one get taste of working with dataframes he do not want go back to nested list.

While I keep it close to your solution, yet Pandas is quite flexible, alternatively, you can create a dataframe with two columns and concatenate it, if you fancy a one-liner, see Is it possible to add several columns at once to a pandas DataFrame?

If restricted to standard lists operations or prefer to modify the list in place. Well, one loop should suffice

for item in list_a:
   item.insert(0, constant2)
   item.insert(0, constant1)

And one change a row in one line

for (i, item) in enumerate(list_a):
    list_a[i] = [constant1, constant2].extend(item)

If you are ok with creating a new list, rather than changing the list_a in place, and prefer use standard list operations, list comprehension would be even more compact and even slightly faster than the loop.

Serge
  • 3,387
  • 3
  • 16
  • 34