Home > front end >  Initialise a list element referring to an earlier element from the same list
Initialise a list element referring to an earlier element from the same list

Time:08-29

Given the list

l = [ "ALPHA ONE", 123, _( "Alpha One" ), _( "ALPHA ONE" ) ]

where elements 2 and 3 (the translated text) are both tied directly to element 0.

Is it possible to define the list in which elements 2 and 3 dynamically refer to element 0? Is there a notation/mechanism for a list element to be initialised by referring to an earlier element?

For example, something along the lines of

l = [ "ALPHA ONE", 123, _( [ 0 ].title() ), _( [ 0 ].upper() ) ]

This would make life easier/safer as I don't want to have to define essentially the text over and over.

CodePudding user response:

From Python 3.8 this is possible using assignment expressions (the walrus operator). Assign the first element to a name using the walrus operator and then reuse this variable in the other elements

l = [(x := "ALPHA ONE"), 123, _(x.title()), _(x.upper())]

CodePudding user response:

Is there a reason you need to put it in a list literal? Also, this seems more like a tuple.

t = "ALPHA ONE"
l = (t, 123, _(t.title()), _(t.upper()))
  • Related