473,395 Members | 1,379 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,395 software developers and data experts.

Noob questions about Python

I have recently (today) just started learning/playing with Python. So
far I am excited and impressed (coming from PHP background).

I have a few questions regarding Python behavior...

val = 'string'
li = list(val)
print li.reverse()

returns nothing, but,

val = 'string'
li = list(val)
li.reverse()
print li

returns what I want. Why does Python do that?

Also I have been playing around with Binary math and noticed that
Python treats:

val = 00110

as the integer 72 instead of returning 00110, why does Python do that?
(and how can I get around it?)

Grateful for any replies!

Oct 17 '07 #1
18 2105
On Oct 17, 3:37 pm, Ixiaus <parnel...@comcast.netwrote:
I have recently (today) just started learning/playing with Python. So
far I am excited and impressed (coming from PHP background).

I have a few questions regarding Python behavior...

val = 'string'
li = list(val)
print li.reverse()

returns nothing, but,

val = 'string'
li = list(val)
li.reverse()
print li

returns what I want. Why does Python do that?
Because list.reverse() modifies a list, it doesn't create and return a
new one.

A common idiom for returning a reversed copy of a list is:
li[::-1]

You can also use the builtin "reversed" -- it doesn't return a list,
but rather a reverse iterator. You can create a list from an iterator
by passing it to the list() initializer, like list(reversed(li)).

Oct 17 '07 #2
Ixiaus a écrit :
I have recently (today) just started learning/playing with Python. So
far I am excited and impressed
Welcome onboard then !-)
(coming from PHP background).

I have a few questions regarding Python behavior...

val = 'string'
li = list(val)
print li.reverse()

returns nothing, but,

val = 'string'
li = list(val)
li.reverse()
print li

returns what I want. Why does Python do that?
list.reverse (like list.sort) is a destructive in-place operation. Not
returning the object is reminder of the destructive nature of the
operation. That's a design choice, whether you agree with it or not
(FWIW, I don't, but I live with it !-)

Note that there's also the reverse() function that returns a reverse
iterator over any sequence, so you could also do:

li = list('allo')
print ''.join(reverse(li))
Also I have been playing around with Binary math and noticed that
Python treats:

val = 00110

as the integer 72 instead of returning 00110, why does Python do that?
Literal integers starting with '0' (zero) are treated as octal. It's a
pretty common convention (like 0x for hexa). FWIW, PHP does just the
same thing.
(and how can I get around it?)
You can't. Python has no literal notation for binary integers so far.
Literal notation for binary ints is not a common feature anyway.

HTH
Oct 17 '07 #3
On Oct 17, 8:37 pm, Ixiaus <parnel...@comcast.netwrote:
I have a few questions regarding Python behavior...
as the integer 72 instead of returning 00110, why does Python do that?
(and how can I get around it?)
You can do this:

def bin(x):
return int(x, 2)

val = bin('00110')

--
Paul Hankin

Oct 17 '07 #4
On 2007-10-17, Bruno Desthuilliers
<bd*****************@free.quelquepart.frwrote:
Ixiaus a écrit :
>val = 00110

as the integer 72 instead of returning 00110, why does Python
do that?

Literal integers starting with '0' (zero) are treated as octal.
It's a pretty common convention (like 0x for hexa). FWIW, PHP
does just the same thing.
>(and how can I get around it?)

You can't. Python has no literal notation for binary integers
so far. Literal notation for binary ints is not a common
feature anyway.
You can obtain a practical workaround using the int built-in
function.
>>int('110', 2)
6

--
Neil Cerutti
Oct 17 '07 #5
Thank you for the quick responses.

I did not know that about integer literals beginning with a '0', so
thank you for the explanation. I never really use PHP except for
handling basic forms and silly web stuff, this is why I picked up
Python because I want to teach myself a more powerful and broad
programming language.

With regard to why I asked: I wanted to learn about Binary math in
conjunction with Python, so I wrote a small function that would return
a base 10 number from a binary number. It is nice to know about the
int() function now.

Just for the sake of it, this was the function I came up with:

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
res.reverse()
print sum(res)

Now that I look at it, I probably don't need that last reverse()
because addition is commutative...

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)

It basically does the same thing int(string, 2) does.

Thank you for the responses!

Oct 17 '07 #6
On Oct 17, 4:58 pm, Ixiaus <parnel...@comcast.netwrote:
Thank you for the quick responses.

I did not know that about integer literals beginning with a '0', so
thank you for the explanation. I never really use PHP except for
handling basic forms and silly web stuff, this is why I picked up
Python because I want to teach myself a more powerful and broad
programming language.

With regard to why I asked: I wanted to learn about Binary math in
conjunction with Python, so I wrote a small function that would return
a base 10 number from a binary number. It is nice to know about the
int() function now.

Just for the sake of it, this was the function I came up with:

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
res.reverse()
print sum(res)

Now that I look at it, I probably don't need that last reverse()
because addition is commutative...

def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)

It basically does the same thing int(string, 2) does.

Thank you for the responses!
You could also get ahold of the gmpy module. You get conversion
to binary and also some useful other binary functions as shown
below:

# the Collatz Conjecture in binary

import gmpy

n = 27
print '%4d %s' % (n,gmpy.digits(n,2).zfill(16))

sv = [] # sequence vector, blocks of contiguous LS 0's

while n != 1:
old_n = n
n = 3*n + 1 # result always even
f = gmpy.scan1(n,0) # find least significant 1 bit
n >>= f # remove LS 0's in one fell swoop
sv.append(f) # record f sequence
PopC = gmpy.popcount(n) # count of 1 bits
HamD = gmpy.hamdist(n,old_n) # bits changed
print '%4d %s' % (n,gmpy.digits(n,2).zfill(16)),
print 'PopC:%2d HamD:%2d' % (PopC,HamD)

print sv

## 27 0000000000011011
## 41 0000000000101001 PopC: 3 HamD: 3
## 31 0000000000011111 PopC: 5 HamD: 4
## 47 0000000000101111 PopC: 5 HamD: 2
## 71 0000000001000111 PopC: 4 HamD: 3
## 107 0000000001101011 PopC: 5 HamD: 3
## 161 0000000010100001 PopC: 3 HamD: 4
## 121 0000000001111001 PopC: 5 HamD: 4
## 91 0000000001011011 PopC: 5 HamD: 2
## 137 0000000010001001 PopC: 3 HamD: 4
## 103 0000000001100111 PopC: 5 HamD: 6
## 155 0000000010011011 PopC: 5 HamD: 6
## 233 0000000011101001 PopC: 5 HamD: 4
## 175 0000000010101111 PopC: 6 HamD: 3
## 263 0000000100000111 PopC: 4 HamD: 4
## 395 0000000110001011 PopC: 5 HamD: 3
## 593 0000001001010001 PopC: 4 HamD: 7
## 445 0000000110111101 PopC: 7 HamD: 7
## 167 0000000010100111 PopC: 5 HamD: 4
## 251 0000000011111011 PopC: 7 HamD: 4
## 377 0000000101111001 PopC: 6 HamD: 3
## 283 0000000100011011 PopC: 5 HamD: 3
## 425 0000000110101001 PopC: 5 HamD: 4
## 319 0000000100111111 PopC: 7 HamD: 4
## 479 0000000111011111 PopC: 8 HamD: 3
## 719 0000001011001111 PopC: 7 HamD: 3
##1079 0000010000110111 PopC: 6 HamD: 7
##1619 0000011001010011 PopC: 6 HamD: 4
##2429 0000100101111101 PopC: 8 HamD: 8
## 911 0000001110001111 PopC: 7 HamD: 7
##1367 0000010101010111 PopC: 7 HamD: 6
##2051 0000100000000011 PopC: 3 HamD: 6
##3077 0000110000000101 PopC: 4 HamD: 3
## 577 0000001001000001 PopC: 3 HamD: 5
## 433 0000000110110001 PopC: 5 HamD: 6
## 325 0000000101000101 PopC: 4 HamD: 5
## 61 0000000000111101 PopC: 5 HamD: 5
## 23 0000000000010111 PopC: 4 HamD: 3
## 35 0000000000100011 PopC: 3 HamD: 3
## 53 0000000000110101 PopC: 4 HamD: 3
## 5 0000000000000101 PopC: 2 HamD: 2
## 1 0000000000000001 PopC: 1 HamD: 1
##[1, 2, 1, 1, 1, 1, 2, 2, 1, 2, 1, 1, 2,
## 1, 1, 1, 2, 3, 1, 1, 2, 1, 2, 1, 1, 1,
## 1, 1, 3, 1, 1, 1, 4, 2, 2, 4, 3, 1, 1,
## 5, 4]

Oct 18 '07 #7
On Oct 17, 5:58 pm, Ixiaus <parnel...@comcast.netwrote:
def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)

It basically does the same thing int(string, 2) does.

Thank you for the responses!
BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)

def baseN(number, N=2):
"""
>>baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0
b = []
while number:
b.append(str(number % N))
number /= N
return ''.join(reversed(b))

Michele Simionato

Oct 18 '07 #8
On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote:
[snip]
>
Note that there's also the reverse() function that returns a reverse
iterator over any sequence, so you could also do:

li = list('allo')
print ''.join(reverse(li))
Note this certainly should've been `reversed()`, with a trailing 'd'.
Oct 18 '07 #9
Stargaming a écrit :
On Wed, 17 Oct 2007 22:05:36 +0200, Bruno Desthuilliers wrote:
[snip]
>Note that there's also the reverse() function that returns a reverse
iterator over any sequence, so you could also do:

li = list('allo')
print ''.join(reverse(li))

Note this certainly should've been `reversed()`, with a trailing 'd'.
2-0 for Stargaming. I'll have to either change glasses, buy a new
keyboard (this one is obviously broken), or learn to both use a keyboard
and re-read what I post.
Oct 18 '07 #10
On Oct 18, 7:06 am, Ixiaus <parnel...@comcast.netwrote:
[...]
I know '<<' is shifting x over by n bits; but could you point me to
some literature that would explain why it is the same as "x*2**n"?
I haven't got literature but I've got a (hopefully straightforward)
explanation:

In binary 2 is 10. When you multiply by 10, you shift all your digits
left by 1 place.
When you multiply by 10**n (which is 1 followed by n zeroes), you
shift all your digits left by n places.

HTH

--
Arnaud
Oct 18 '07 #11
On Wed, 17 Oct 2007 23:06:24 -0700, Ixiaus wrote:
I know '<<' is shifting x over by n bits; but could you point me to some
literature that would explain why it is the same as "x*2**n"? (Googling
only returns bit shift, but doesn't necessarily explain the manner in
which you are using it)
In decimal, multiplying by ten shifts the digits to the left by one place:

31 * 10 =310
310 * 10 =3100
3100 * 10 =31000

In binary, multiplying by two shifts the bits to the left by one place:

101 * 10 =1010
1010 * 10 =10100
10100 * 10 =101000

Because the underlying numbers are the same regardless of what base we
use to write it in, bit-shifts to the left are equivalent to repeated
multiplication by two regardless of the display base. Hence:
>>7 << 1
14
>>14 << 1
28
>>28 << 1
56

or to do it another way:
>>7 << 3 # multiplication by 2**3
56

Similarly, a bit-shift to the right is equivalent to dividing by two and
dropping any remainder.
I will have to read up more on Generators, but maybe you can give me a
lowdown on why
sum([1 << k for k, i in enumerate(reversed(val)) if int(i)]) is less
efficient than using a Generator (is the generator a 'temporary' list?)
sum(1 << k for k, i in enumerate(reversed(val)) if int(i))
The list comprehension:

[1 << k for k, i in enumerate(reversed(val)) if int(i)]

creates the entire list first. That potentially can require a lot of
memory, leading to all sorts of complicated memory shuffles as the list
is resized, paging, etc.

Using a generator expression means that you avoid creating the entire
list all in one go. That saves you memory, which may mean that you save
time.

However, for small sets of input, it is likely that the overhead of
creating the generator in the first place outweighs the saving of not
creating the whole list.

The definition of "small" depends on what you are trying to do. In my
tests, I have found that sum(list comprehension) is marginally faster
than sum(generator expression) even for 10,000 items.
--
Steven
Oct 18 '07 #12
On Oct 18, 7:05 am, Michele Simionato <michele.simion...@gmail.com>
wrote:
On Oct 17, 5:58 pm, Ixiaus <parnel...@comcast.netwrote:
def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)
It basically does the same thing int(string, 2) does.
Thank you for the responses!

BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)
It returns '' when number == 0, so you need to test for that case:
def baseN(number, N=2):
"""
>>baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0
if number == 0:
return "0"
b = []
while number:
b.append(str(number % N))
number /= N
return ''.join(reversed(b))

Michele Simionato

Oct 18 '07 #13
That was a very helpful answer Steven, thank you for taking the time
to write it!

Oct 19 '07 #14
On Oct 18, 7:44 pm, MRAB <goo...@mrabarnett.plus.comwrote:
It returns '' when number == 0, so you need to test for that case:
def baseN(number, N=2):
"""
>>baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0

if number == 0:
return "0"
b = []
while number:
b.append(str(number % N))
number /= N
return ''.join(reversed(b))
Right, or you can just change the last line:

return ''.join(reversed(b)) or '0'
Michele Simionato

Oct 19 '07 #15
On Oct 19, 1:44 am, MRAB <goo...@mrabarnett.plus.comwrote:
On Oct 18, 7:05 am, Michele Simionato <michele.simion...@gmail.com>
wrote:On Oct 17, 5:58 pm, Ixiaus <parnel...@comcast.netwrote:
def bin2dec(val):
li = list(val)
li.reverse()
res = [int(li[x])*2**x for x in range(len(li))]
print sum(res)
It basically does the same thing int(string, 2) does.
Thank you for the responses!
BTW, here is the reverse function dec2bin, so that you can
bang your head on it for a while ;)

It returns '' when number == 0, so you need to test for that case:
def baseN(number, N=2):
"""
>>baseN(9, 2)
'1001'
"""
assert 2 <= N <= 10
assert isinstance(number, int) and number >= 0

if number == 0:
return "0"
Hey,

Isn't
if not number:
return "0"

faster?

Oct 19 '07 #16
On 2007-10-19, co*********@gmail.com <co*********@gmail.comwrote:
On Oct 19, 1:44 am, MRAB <goo...@mrabarnett.plus.comwrote:
>On Oct 18, 7:05 am, Michele Simionato <michele.simion...@gmail.com>

if number == 0:
return "0"

Hey,

Isn't
if not number:
return "0"

faster?
Depends on who is parsing it.

If a computer, possibly a few micro-seconds (if the Python byte-code generator
doesn't optimize it away).

If a human, then it is slower by at least a second.
Since I prefer to optimize on my time rather than CPU time, I'd prefer the
first version

Albert
Oct 19 '07 #17
"Arnaud Delobelle" <arno....email.comwrote:
In binary 2 is 10. When you multiply by 10, you shift all your digits
left by 1 place.
When you multiply by 10**n (which is 1 followed by n zeroes), you
shift all your digits left by n places.
I read somewhere:

Only 1 person in 1000 understands binary.
The other 111 don't have a clue.

- Hendrik

Oct 19 '07 #18
On 2007-10-19, Hendrik van Rooyen <ma**@microcorp.co.zawrote:
"Arnaud Delobelle" <arno....email.comwrote:
>In binary 2 is 10. When you multiply by 10, you shift all your digits
left by 1 place.
When you multiply by 10**n (which is 1 followed by n zeroes), you
shift all your digits left by n places.

I read somewhere:

Only 1 person in 1000 understands binary.
The other 111 don't have a clue.
There are only 10 kinds of people: those who understand binary
and those who don't.

--
Grant Edwards grante Yow! Will this never-ending
at series of PLEASURABLE
visi.com EVENTS never cease?
Oct 19 '07 #19

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

Similar topics

7
by: administrata | last post by:
Is it possible? I tried... I = "John" print \ """ I used to love pizza"""
10
by: Matt Hollingsworth | last post by:
Hello, Very new to python, so a noob question. When I've written stuff in JavaScript or MEL in the past, I've always adopted the variable naming convention of using a $ as the first character...
3
by: digitalsubjunctive | last post by:
Hey, I just started on Python and have a few questions I couldn't find answers to on the Python site or it's tutorial. 1. I notice a few "compiled python" files (indicated by reddish snake...
5
by: Omar | last post by:
Hi all...this is a good group so I'm sure you'll tolerate some more noobish questions... 1) I'm also learning to program flash movies while I learn to do python. How can one implement flash...
2
by: Carnell, James E | last post by:
I am thinking about purchasing a book, but wanted to make sure I could get through the code that implements what the book is about (Artificial Intelligence a Modern Approach). Anyway, I'm not a...
1
by: Ixiaus | last post by:
I have recently (today) just started learning/playing with Python. So far I am excited and impressed (coming from PHP background). I have a few questions regarding Python behavior... val =...
2
by: kj | last post by:
I'm a Python noob, and haven't yet figured out my way around the Python documentation. For example, suppose I learn about some great module foo.bar.baz, and when I run the python interpreter and...
4
by: larry | last post by:
Ok I'm a Python noob, been doing OK so far, working on a data conversion program and want to create some character image files from an 8-bit ROM file. Creating the image I've got down, I open...
0
by: fatality123 | last post by:
hi all I am new to both python and image processing. My task is to use python and tk to create a tool which can convert between the difft RGb color spaces like 565,888,444 etc and difft YCbCr color...
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: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.