Re: Lists in Python versus other languages

Liste des GroupesRevenir à cl python 
Sujet : Re: Lists in Python versus other languages
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.python
Date : 24. Jun 2024, 13:25:13
Autres entêtes
Organisation : Stefan Ram
Message-ID : <calls-20240624122249@ram.dialup.fu-berlin.de>
References : 1 2
Sebastian Wells <sebastian@here.com.invalid> wrote or quoted:
The thing that makes Python tuples different
from Python lists is that tuples are
immutable. Lisp doesn't have a type that
is "a list (or array) but it's immutable."

  Yeah, I was thinking about the mathematical term "tuple" here.

  In math, one doesn't really have just "tuples," but rather
  "2-tuples," "3-tuples," and so on. The number is a fixed part of the
  tuple's type. So, if one's dealing with a tuple representation made
  of dotted pairs in LISP, one'd need to know how many components are
  in it to interpret it correctly. While a list in LISP (with something
  like "replace CDR") can be dynamically extended, one can't extend a
  tuple because its size is fixed. In that sense, a LISP tuple (in the
  sense suggested by me) is more static than a LISP list.

It doesn't yield actual lists or tuples, so you can't use  it the
way OP was suggesting,  that is, the way you'd use the corresponding
Lisp feature.

  If one wants to parse Python code, like a tuple, the ast module
  does all the heavy lifting to set up an AST. Turning that into
  a real Python tuple takes just a bit of postprocessing.

  main.py

import ast as _ast

source = r'''
( 0, 1,( 2, 3 ))
'''[ 1: -1 ]

def postprocess( parse_result ):
    if isinstance( parse_result, _ast.Module ):
        return postprocess( parse_result.body[ 0 ] )
    elif isinstance( parse_result, _ast.Expr ):
        return postprocess( parse_result.value )
    elif isinstance( parse_result, _ast.Tuple ):
        return \
        tuple( postprocess( element )for element in parse_result.elts )
    elif isinstance( parse_result, _ast.Constant ):
        return parse_result.value

print( postprocess( _ast.parse( source )))

  stdout

(0, 1, (2, 3))

  In the case of simple tuples (with no calls or something),
  one can just use "literal_eval".

  main.py

import ast

print( ast.literal_eval( '( 0, 1,( 2, 3 ))' ))

  stdout

(0, 1, (2, 3))

  .

Date Sujet#  Auteur
24 Jun 24 * Lists in Python versus other languages4Stefan Ram
24 Jun 24 `* Re: Lists in Python versus other languages3Sebastian Wells
24 Jun 24  `* Re: Lists in Python versus other languages2Stefan Ram
24 Jun 24   `- Re: Lists in Python versus other languages1Stefan Ram

Haut de la page

Les messages affichés proviennent d'usenet.

NewsPortal