What's correct Python syntax?

Peter Otten __peter__ at web.de
Tue Jan 14 06:33:26 EST 2014


Igor Korot wrote:

> I am actually looking for a way to get a result from split which is
> sliced the way I want. Like in my example above.
> I mean I can probably make more variable by creating a tuple, but why?
> What is the purpose if I want only couple elements out of split.
> Doing it Perl way does not help:
> 
> C:\Documents and Settings\Igor.FORDANWORK\Desktop\winpdb>python
> Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
>>>> test = "I,like,my,chocolate"
>>>> print test.split(',')[2,3]
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> TypeError: list indices must be integers, not tuple
> 
> I can do it this way:
> 
>>>> testlist = test.split(',')
>>>> print testlist[2]
> my
> 
> but it will needlessly creates a list on which I will access by the index.
> 
> Why? All I need is couple of values out of n-dimensional list (array).

Python has no dedicated syntax for picking arbitrary items from a list 
If you are only concerned about printing use format():

>>> items = ["alpha", "beta", "gamma", "delta"]
>>> print "{1} {3} {0}".format(*items)
beta delta alpha

If you want to work with the values use operator.itemgetter():

>>> from operator import itemgetter
>>> itemgetter(1, 0, -1)(items)
('beta', 'alpha', 'delta')






More information about the Python-list mailing list