473,809 Members | 2,740 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2154
On Oct 17, 3:37 pm, Ixiaus <parnel...@comc ast.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(l i)).

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...@comc ast.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.quel quepart.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...@comc ast.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 000000000001101 1
## 41 000000000010100 1 PopC: 3 HamD: 3
## 31 000000000001111 1 PopC: 5 HamD: 4
## 47 000000000010111 1 PopC: 5 HamD: 2
## 71 000000000100011 1 PopC: 4 HamD: 3
## 107 000000000110101 1 PopC: 5 HamD: 3
## 161 000000001010000 1 PopC: 3 HamD: 4
## 121 000000000111100 1 PopC: 5 HamD: 4
## 91 000000000101101 1 PopC: 5 HamD: 2
## 137 000000001000100 1 PopC: 3 HamD: 4
## 103 000000000110011 1 PopC: 5 HamD: 6
## 155 000000001001101 1 PopC: 5 HamD: 6
## 233 000000001110100 1 PopC: 5 HamD: 4
## 175 000000001010111 1 PopC: 6 HamD: 3
## 263 000000010000011 1 PopC: 4 HamD: 4
## 395 000000011000101 1 PopC: 5 HamD: 3
## 593 000000100101000 1 PopC: 4 HamD: 7
## 445 000000011011110 1 PopC: 7 HamD: 7
## 167 000000001010011 1 PopC: 5 HamD: 4
## 251 000000001111101 1 PopC: 7 HamD: 4
## 377 000000010111100 1 PopC: 6 HamD: 3
## 283 000000010001101 1 PopC: 5 HamD: 3
## 425 000000011010100 1 PopC: 5 HamD: 4
## 319 000000010011111 1 PopC: 7 HamD: 4
## 479 000000011101111 1 PopC: 8 HamD: 3
## 719 000000101100111 1 PopC: 7 HamD: 3
##1079 000001000011011 1 PopC: 6 HamD: 7
##1619 000001100101001 1 PopC: 6 HamD: 4
##2429 000010010111110 1 PopC: 8 HamD: 8
## 911 000000111000111 1 PopC: 7 HamD: 7
##1367 000001010101011 1 PopC: 7 HamD: 6
##2051 000010000000001 1 PopC: 3 HamD: 6
##3077 000011000000010 1 PopC: 4 HamD: 3
## 577 000000100100000 1 PopC: 3 HamD: 5
## 433 000000011011000 1 PopC: 5 HamD: 6
## 325 000000010100010 1 PopC: 4 HamD: 5
## 61 000000000011110 1 PopC: 5 HamD: 5
## 23 000000000001011 1 PopC: 4 HamD: 3
## 35 000000000010001 1 PopC: 3 HamD: 3
## 53 000000000011010 1 PopC: 4 HamD: 3
## 5 000000000000010 1 PopC: 2 HamD: 2
## 1 000000000000000 1 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...@comc ast.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(numb er, int) and number >= 0
b = []
while number:
b.append(str(nu mber % N))
number /= N
return ''.join(reverse d(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

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

Similar topics

7
1754
by: administrata | last post by:
Is it possible? I tried... I = "John" print \ """ I used to love pizza"""
10
2142
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 (no, I don't use perl, never have). Not possible in python. What are some good options that people commonly use so that they can easily and quickly identify variable with just a glance? When I was writing stuff in SoftImage XSI/JScript, many of...
3
1351
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 icons), I thought Python didn't need to be compiled? This is my first venture into programming, but if it doesn't need to be compiled why compile it? 2. What is a .pwy file?
5
1202
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 movies into their python code? 2) besides Chieh's tutorials on the python.org site, anyone know of any other video tutorials for python? this style of learning suites me well.
2
1942
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 very good programmer and OOP is still sinking in, so please don't answer my questions like I really know anything. MY QUESTION: What is a slot? In class Object below the __init__ has a slot. Note: The slot makes use of a data object called...
1
223
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 = 'string' li = list(val) print li.reverse() returns nothing, but,
2
1042
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 type "import foo.bar.baz", lo and behold, it is already installed on our system, which means that (knowing that our system is pretty bare-bones as far as python goes) most likely foo.bar.baz is part of the standard python installation.
4
2110
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 the file and use TK to draw the images... but 1) It does not seem to end (running in IDLE), I have to kill the process to retry it seems tkinter does not close(?)
0
1404
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 spaces like 444,422,420and 411. I read abt PIL and installed it.I am working in Windows XP environment. to do this task i am facing the following problems: 1.read and write image files in difft formats like ppm,pgm,bmp in both binary and ascii...
0
9721
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
10639
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10120
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
9200
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
6881
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5550
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
5688
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3861
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3015
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.