-1

Say I have a list of strings:

myList = ['apple','banana','orange']

and another string saved into a single variable:

myVariable = 'fudge'

I want to add the suffix _df2 to every element in myList, and also to myVariable. Therefore, I want my result to look like this:

>> myList
['apple_df2', 'banana_df2', 'orange_df2']

>> myVariable
'fudge_df2'

Currently I am achieving this with the following code:

myList = [fruit + '_df2' for fruit in myList]
myVariable = myVariable + '_df2'

I am wondering, however, since I am adding the same suffix both times, is there a way to sum these two steps up into one?

dejanualex
  • 3,872
  • 6
  • 22
  • 37

2 Answers2

0

Create a single list headed by your singleton item, universally apply the modification, then unpack in the same order.

myVariable, *myList = [x + '_df2' for x in [myVariable, *myList]]

I would probably still prefer the two-line solution, though. You aren't just appending the same value to each element; you also need to preserve the list structure of the original list.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • Star assignments are covered in [PEP 448](https://www.python.org/dev/peps/pep-0448/) Works the other way too: `*myList,myVariable=[e+addition for e in myList+[myVariable]]` – dawg Feb 01 '21 at 15:44
-1

You could do the following, but as @YevhenKuzmovych says, its not a good solution.

myList, myVariable = [fruit + '_df2' for fruit in myList], myVariable + '_df2'
Scott Hunter
  • 48,888
  • 12
  • 60
  • 101
  • There's absolutely no benefit of doing that. There are still two operations there (3 or 4 if you count packing, unpacking). And now it's less readable. – Yevhen Kuzmovych Feb 01 '21 at 14:43