A few words about Python’s extended slices

One thing that most Python users learn at the very beginning are list slices – defining a part of the list using the samplelist[begin:end] syntax. It’s great thing, but – surprisingly – many people don’t even know, that there’s different syntaxt for this, containing one additional parameter – “step”: samplelist[begin:end:step]. How does it work?

Continue reading

5 Python features you might not know about

Few days ago I was talking with my friend about most useful Python features we use almost every day. It was not about any sophisticated tools or libraries, but about the things we use often and which are “given” by the language and its syntax itself – the ones which we like just because they’re “pythonic”. I’ve picked and some of them, which are easy to describe in short devblog article. Even if most of these things should be known for most of the Python developers, I bet that many of you don’t know about at least one of them or just use to forget about using it ;)

Continue reading

Strange behavior of default function parameters in Python

Sometimes things don’t work in the way we want them to. Today I was asked why this piece of code is not working properly (OK, given problem was a bit different and much more “real-life-applicable”, but it’s just an example):

1
2
3
4
5
6
7
8
9
def mypush(val, mylist=[]):
	mylist.append(val)
	print mylist, ': ', id(mylist)
 
lst = []
mypush(1, lst)
mypush(2, lst)
mypush(1)
mypush(2)

The output is:

1
2
3
4
[1]    :  139750946213184
[1, 2] :  139750946213184
[1]    :  139750946218496
[1, 2] :  139750946218496

What’s wrong with it? NOTHING – that’s the way Python should and will behave in such case.

Do you agree? If yes – stop reading, because you won’t learn anything new. Go to XKCD instead. If no – here’s a brief explaination:

Continue reading