473,594 Members | 2,854 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Partially unpacking a sequence

I have a list y
y ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
'19.500', '224']

from which I want to extract only the 2nd and 4th item by partially
unpacking the list. So I trieda,b = y[2,4] Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

Out of curiosity, I trieda,b = y[2:4]
a '04276410' b

'18.500'

Why does this work (to a point - it gives me items 2 and 3, not 2 and
4 as I require) and not my first attempt? What is the right syntax to
use when partially upacking a sequence?

Thanks in advance

Thomas Philips

Apr 6 '06 #1
9 1410
<tk****@hotmail .com> wrote in message
news:11******** **************@ z34g2000cwc.goo glegroups.com.. .
I have a list y
y ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
'19.500', '224']

from which I want to extract only the 2nd and 4th item by partially
unpacking the list. So I trieda,b = y[2,4] Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

Out of curiosity, I trieda,b = y[2:4]
a '04276410' b

'18.500'

Why does this work (to a point - it gives me items 2 and 3, not 2 and
4 as I require) and not my first attempt? What is the right syntax to
use when partially upacking a sequence?

Thanks in advance

Thomas Philips


a,b = y[2],y[4]

or

a,b = y[2:5:2]

or

a,b = ( y[i] for i in (2,4) )
-- Paul
Apr 6 '06 #2
tk****@hotmail. com wrote:
I have a list y
y ['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
'19.500', '224']

from which I want to extract only the 2nd and 4th item by partially
unpacking the list. So I trieda,b = y[2,4] Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

Out of curiosity, I trieda,b = y[2:4]
a '04276410' b

'18.500'

Why does this work (to a point - it gives me items 2 and 3, not 2 and
4 as I require) and not my first attempt? What is the right syntax to
use when partially upacking a sequence?


if you want two items, fetch two items:

a = y[2]
b = y[4]

y[2:4] is a 2-item slice starting at index 2 and ending *before* index 4.
see the documentation for more on slicing.

</F>

Apr 6 '06 #3
"Paul McGuire" <pt***@austin.r r._bogus_.com> wrote in message
news:Fk******** *********@torna do.texas.rr.com ...
<tk****@hotmail .com> wrote in message
news:11******** **************@ z34g2000cwc.goo glegroups.com.. .
I have a list y
>>y

['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
'19.500', '224']

from which I want to extract only the 2nd and 4th item by partially
unpacking the list. So I tried
>>a,b = y[2,4]

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

Out of curiosity, I tried
>>a,b = y[2:4]
>>a

'04276410'
>> b

'18.500'

Why does this work (to a point - it gives me items 2 and 3, not 2 and
4 as I require) and not my first attempt? What is the right syntax to
use when partially upacking a sequence?

Thanks in advance

Thomas Philips


a,b = y[2],y[4]

or

a,b = y[2:5:2]

or

a,b = ( y[i] for i in (2,4) )
-- Paul


Forgot one:

_,_,a,_,b,_,_,_ = y

There actually is some merit to this form. If the structure of y changes
sometime in the future (specifically if a field is added or removed), this
statement will fail noisily, calling your attention to this change. But if
a new field is added, say at the front of the list, the previous methods
will all silently succeed, but now giving you the values formerly known as
y[1] and y[3].

-- Paul
Apr 6 '06 #4
Thank you, everyone, for resolving my question. At one point, while
trying to solve the problem, I typed
y[1,3]

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

The error message gave me no clue as to what I was doing wrong (in my
mind, I was just writing out the elements of a range), and I thought
perhaps that my inclusion of a comma was the problem. Perhaps a more
explicit error message would have helped.

Another solution, I suppose, is to use a list comprehension. Store the
indices in a list x. For example, let x = [1,5,4]. Then

a,b,c = [y[i] for i in x]

Thanks

Thomas Philips

Apr 6 '06 #5
Paul McGuire wrote:
Forgot one:

_,_,a,_,b,_,_,_ = y

There actually is some merit to this form. If the structure of y changes
sometime in the future (specifically if a field is added or removed), this
statement will fail noisily, calling your attention to this change. But if
a new field is added, say at the front of the list, the previous methods
will all silently succeed, but now giving you the values formerly known as
y[1] and y[3].


if this is likely to happen, an straightforward assert is a lot easier to parse than
a one-two-a-three-oops-one-two-a-four-five-etc number of underscores:

assert len(y) == 8
a = y[2]
b = y[4]

</F>

Apr 6 '06 #6
tk****@hotmail. com enlightened us with:
y[1,3]
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

The error message gave me no clue as to what I was doing wrong (in
my mind, I was just writing out the elements of a range), and I
thought perhaps that my inclusion of a comma was the problem.


You thought correct. List indices must be integers, not tuples.
Perhaps a more explicit error message would have helped.


Why? You thought the right thing.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
Apr 6 '06 #7
>> Thank you, everyone, for resolving my question. At one point, while
trying to solve the problem, I typed
> y[1,3]


Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

The error message gave me no clue as to what I was doing wrong (in my
mind, I was just writing out the elements of a range), and I thought
perhaps that my inclusion of a comma was the problem. Perhaps a more
explicit error message would have helped.

The error message is correct because in y[1, 3] "1, 3" is recognized by
the interpreter
as tuple. Python goodie or snakebite that is...

Apr 6 '06 #8
tk****@hotmail. com wrote:
Thank you, everyone, for resolving my question. At one point, while
trying to solve the problem, I typed
y[1,3]

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
TypeError: list indices must be integers

The error message gave me no clue as to what I was doing wrong (in my
mind, I was just writing out the elements of a range), and I thought
perhaps that my inclusion of a comma was the problem. Perhaps a more
explicit error message would have helped.


the problem is that the *compiler* doesn't know what "y" is, and y[1,3]
is a perfectly valid way to access e.g. a dictionary or a multidimensiona l
array. so it's the list implementation that has to do the complaining, and
all it knows is that it wants an integer index, and got something else.

maybe something like

TypeError: list indices must be integers (got tuple)

would have been less confusing; feel free to add a suggestion to the bug
tracker:

http://sourceforge.net/tracker/?grou...70&atid=105470

</F>

Apr 7 '06 #9
tk****@hotmail. com wrote:
I have a list y
y
['20001201', 'ARRO', '04276410', '18.500', '19.500', '18.500',
'19.500', '224']

from which I want to extract only the 2nd and 4th item

by partially
unpacking the list. So I tried
a,b = y[2,4]


Mmm, so lovely and meaningful names !-)

FWIW, and since nobody seemed to mention it, list indexes are
zero-based, so the second element of a list is at index 1 and the fourth
at index 3.

Also, a GoodPractice(tm ) is to use named constants instead of magic
numbers. Here we don't have a clue about why these 2 elements are so
specials. Looking at the example list (which - semantically - should be
a tuple, not a list) I could wild-guess that the 2nd item is a reference
and the fourth a price, so:

REF_INDEX = 1 # lists are zero-based
PRICE_INDEX = 3

ref, price = y[REF_INDEX], y[PRICE_INDEX]

And finally, since this list is clearly structured data, wrapping it
into an object to hide away implementation details *may* help -
depending on the context, of course !-)
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
Apr 7 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

32
2818
by: Dave Benjamin | last post by:
Hey all, I just realized you can very easily implement a sequence grouping function using Python 2.3's fancy slicing support: def group(values, size): return map(None, * for i in range(size)]) >>> group(range(20), 4)
2
1757
by: george young | last post by:
I came across an cool python feature that I've not seen discussed. This may be *implied* by the language reference manual http://docs.python.org/ref/assignment.html], but it was never obvious to me: An assignment statement can unpack a sequence, binding it's values to explicit names, e.g.: r,g,b = color_tuple and most of us use this frequently. However, what I never saw was
8
3622
by: Paul McGuire | last post by:
I'm trying to manage some configuration data in a list of tuples, and I unpack the values with something like this: configList = for data in configList: name,a,b,c = data ... do something with a,b, and c Now I would like to add a special fourth config value to "T": ("T",1,5,4,0.005),
5
1979
by: Chris | last post by:
Hi I'm attempting to write a client for an existing p2p network. The protocol defines that ints are packed into 4 bytes for transfer. // Creating the byte vector using the following is fine: for(int i=3; i>=0; i--) { vecBuff.push_back(value&0xff); value/=256; }
11
1626
by: harold | last post by:
Dear all, Maybe I stared on the monitor for too long, because I cannot find the bug ... My script "transition_filter.py" starts with the following lines: import sys for line in sys.stdin : try :
16
1330
by: John Salerno | last post by:
I'm a little confused, but I'm sure this is something trivial. I'm confused about why this works: ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) (('hello', 'goodbye'), ('more', 'less'), ('something', 'nothing'), ('good', 'bad')) print x
5
1511
by: ram | last post by:
Stupid question #983098403: I can't seem to pass an unpacked sequence and keyword arguments to a function at the same time. What am I doing wrong? def f(*args, **kw): for a in args: print 'arg:', a for (k,v) in kw.iteritems(): print k, '=', v
4
4611
by: McA | last post by:
Hi all, probably a dumb question, but I didn't find something elegant for my problem so far. In perl you can unpack the element of a list to variables similar as in python (a, b, c = ), but the number of variables need not to fit the number of list elements. That means, if you have less list elements variables are filled with
11
7101
by: mjahabarsadiq | last post by:
Hi I have created a web application. I am using ant to build the war and deploy in tomcat. The war file is deployed under "TOMCATE_HOME/work/standalone/localhost/onlineres.war". I have my source files in "D:\Sadiq\Projects\Onlineres". The folder structure is as follows. 1) D:\Sadiq\Projects\Onlineres: This folder is having the context.xml, web.xml, build.xml and build.properties files.
0
7946
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8374
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8240
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6661
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
3867
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
3903
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2389
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1482
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1216
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.