473,387 Members | 1,749 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

list mutability

hi im having this code

l = [1, 3, 5, 'D', 1, 2, 3, 4, 5, 6, 7, 'A', 'S', 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A']

why i need to copy x list? can someone explain me. If i dont copy it i get this
result:
>>took_num_range(l)
[[1, 2, 3, 4, 5, 6, 7], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4,
3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]]

but if i copy it i get result as im looking for
>>took_num_range(l)
[[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3], [8, 7, 6, 5, 4, 3, 2], [7, 6, 5,
4, 3, 2, 1], [6, 5, 4, 3, 2, 1, 0]]
>>>
def took_num_range(l):
j = []
x = []
for i in l:
if type(i) is int and len(x) == 7:
j.append(x)
x = x[:] # im mean here
x.pop(0)
if type(i) is int and len(x) < 7:
x.append(i)
if type(i) is not int and len(x) == 7:
j.append(x)
x = []
if type(i) is not int and len(x) != 7:
x = []
return j
thx
Feb 18 '08 #1
1 1241
On Feb 19, 5:09 am, gigs <g...@hi.t-com.hrwrote:
hi im having this code

l = [1, 3, 5, 'D', 1, 2, 3, 4, 5, 6, 7, 'A', 'S', 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A']

why i need to copy x list? can someone explain me. If i dont copy it i get this
result:
>>took_num_range(l)
[[1, 2, 3, 4, 5, 6, 7], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0], [6, 5, 4,
3, 2, 1, 0], [6, 5, 4, 3, 2, 1, 0]]

but if i copy it i get result as im looking for
>>took_num_range(l)
[[1, 2, 3, 4, 5, 6, 7], [9, 8, 7, 6, 5, 4, 3], [8, 7, 6, 5, 4, 3, 2], [7, 6, 5,
4, 3, 2, 1], [6, 5, 4, 3, 2, 1, 0]]
>>>

def took_num_range(l):
j = []
x = []
for i in l:
if type(i) is int and len(x) == 7:
j.append(x)
x = x[:] # im mean here
x.pop(0)
j.append(x) saves a reference to the same list that x refers to. So
when you later mutate that one list, all references in j refer to the
mutated list.

Instead of
x = x[:]
x.pop(0)
which copies the contents twice, you can do
x = x[1:]

In a more complicated example, it would be better to take a copy at
each point:

j.append(x[:])

.... then you are sure you have a photo of x and it doesn't matter how/
when you mutate x later.
if type(i) is int and len(x) < 7:
This is a big trap for the casual reader (len(x) may have changed
since the previous "if" statement) ... see below.
x.append(i)
if type(i) is not int and len(x) == 7:
j.append(x)
x = []
if type(i) is not int and len(x) != 7:
x = []
What do you want to do if your input ends with 7 integers and no
letter, e.g.
[1,2,3,'A',1,2,3,4,5,6,7]
?
return j
Some suggestions:
1. use meaningful names
2. don't have hard-wired numbers like 7
3. use "else" and "elif" as appropriate to avoid repeating conditions
unnecessarily.

Here's a suggested replacement for your code, tested to the extent
shown:

C:\junk>type tooknumrange.py
def took_num_range(seq, size, grab_end=False):
result = []
queue = []
for item in seq:
if isinstance(item, int):
if len(queue) == size:
result.append(queue)
queue = queue[1:]
queue.append(item)
else:
if len(queue) == size:
result.append(queue)
queue = []
if grab_end and len(queue) == size:
result.append(queue)
return result

test1 = [
1, 3, 5, 'D',
1, 2, 3, 4, 5, 6, 7, 'A',
'S',
9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 'A',
]
test1r = [
[1, 2, 3, 4, 5, 6, 7],
[9, 8, 7, 6, 5, 4, 3],
[8, 7, 6, 5, 4, 3, 2],
[7, 6, 5, 4, 3, 2, 1],
[6, 5, 4, 3, 2, 1, 0],
]
test2 = [1, 2, 3, 4, 5]
test2r = [[1, 2, 3, 4, 5]] ### or is it [] ???
tests = [
(test1, test1r, 7, False),
(test2, [], 5, False),
(test2, test2r, 5, True),
]

failed = 0
for tno, (tseq, tresult, tsize, tgrab) in enumerate(tests):
aresult = took_num_range(tseq, tsize, grab_end=tgrab)
if aresult != tresult:
failed += 1
print 'Test %d failed' % (tno+1)
print 'Expected:', tresult
print 'Actual :', aresult
print 'Failed %d test(s) out of %d' % (failed, len(tests))
C:\junk>tooknumrange.py
Failed 0 test(s) out of 3

HTH,
John
Feb 18 '08 #2

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

Similar topics

17
by: Gordon Airport | last post by:
Has anyone suggested introducing a mutable string type (yes, of course) and distinguishing them from standard strings by the quote type - single or double? As far as I know ' and " are currently...
46
by: J.R. | last post by:
Hi folks, The python can only support passing value in function call (right?), I'm wondering how to effectively pass a large parameter, such as a large list or dictionary? It could achieved...
41
by: Xah Lee | last post by:
here's another interesting algorithmic exercise, again from part of a larger program in the previous series. Here's the original Perl documentation: =pod merge($pairings) takes a list of...
6
by: massimo | last post by:
Hey, I wrote this program which should take the numbers entered and sort them out. It doesnąt matter what order, if decreasing or increasing. I guess I'm confused in the sorting part. Anyone...
57
by: pinkfloydhomer | last post by:
Isn't there an easier way than lst = ... ?
10
by: Kent | last post by:
Hi! I want to store data (of enemys in a game) as a linked list, each node will look something like the following: struct node { double x,y; // x and y position coordinates struct enemy...
90
by: Christoph Zwerschke | last post by:
Ok, the answer is easy: For historical reasons - built-in sets exist only since Python 2.4. Anyway, I was thinking about whether it would be possible and desirable to change the old behavior in...
17
by: ex_ottoyuhr | last post by:
I'm trying to create a function that can take arguments, say, foo and bar, and modify the original copies of foo and bar as well as its local versions -- the equivalent of C++ funct(&foo, &bar). ...
43
by: michael.f.ellis | last post by:
The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

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.