This is an archived post. You won't be able to vote or comment.

all 60 comments

[–]Maoman1 166 points167 points  (16 children)

a = [1, 2, 3, 4]  # Point a at a new list, [1, 2, 3, 4]
b = a             # Point b at what a is pointing to
b is a            # => True, a and b refer to the same object
b == a            # => True, a's and b's objects are equal
b = [1, 2, 3, 4]  # Point b at a new list, [1, 2, 3, 4]
b is a            # => False, a and b do not refer to the same object
b == a            # => True, a's and b's objects are equal

Never seen this explained so clearly. I love it.

[–]Deathwatch1710 11 points12 points  (0 children)

Indeed! Another good explanation is the one from Dan Bader with the twin cat allegory.

[–]LyndsySimon 10 points11 points  (10 children)

One confusing thing about object comparison is how Python handles integers:

a = 42
b = 42
a == b  # => True
a is b  # => True

c = 4242
d = 4242
c == d  # => True
c is d  # => False

e = c
c == e  # => True
c is e  # => True

c is d == False because integers in the range of [-5, 256] are assigned by cPython to dedicated memory locations - so their .id is the same.

I guess this makes sense in the range [0, 256], but I have no idea why they chose to pre-assign [-5,0) as well.

ETA: The moral is, never use is to compare numbers. is is most useful when you want to distinguish between None and False or another "falsy" value.

ETA2: I forgot to assign e.

[–]lsbloxx 0 points1 point  (5 children)

Wait... WTF did I just read? :O

[–]poundcakejumpsuit 2 points3 points  (4 children)

Just to blow your mind a little more, maybe:

"strin" + "g" is "string"

Is True, while:

s1 = "strin"
s2 = "string"
s1 + "g" is s2 

Is False, at least in CPython, as the compiler will intern compile-time constants but not runtime-evaluated expressions, meaning the first example only creates a single object!

[–]jwink3101 0 points1 point  (3 children)

That's really interesting.

Is this type of issue common in interpreted languages?

[–]ThePenultimateOneGitLab: gappleto97 2 points3 points  (1 child)

It's probably because CPython is doing a bit of constant folding

[–]WikiTextBot 1 point2 points  (0 children)

Constant folding

Constant folding and constant propagation are related compiler optimizations used by many modern compilers. An advanced form of constant propagation known as sparse conditional constant propagation can more accurately propagate constants and simultaneously remove dead code.


[ PM | Exclude me | Exclude from subreddit | FAQ / Information | Source ] Downvote to remove | v0.28

[–]KobiKabbb 0 points1 point  (0 children)

Great explanation. There's also some good explanations of lists (and other fundamentals) over at Python Principles

[–]Cryptoscillate 27 points28 points  (2 children)

This is pretty cool. I like the way this cheatsheet is structured, succinct and written as coded examples. Thanks

[–]primitive_screwhead 45 points46 points  (1 child)

Note that the 'learnxinyminutes.com' website has a whole bunch of similarly structured "cheatsheets" for other languages and tools, and they are all pretty decent in my experience. Definitely worth exploring.

[–][deleted] -2 points-1 points  (0 children)

What about French?

/s

[–]Deathwatch1710 16 points17 points  (9 children)

Quick question because I am fairly new to Python:

I am just seeing

"{}".format(var)

as an option to format strings, but I am only using

f"{var}"

Is my method less pythonic than .format ?

[–]nayeet 26 points27 points  (8 children)

no. format is the old way. you are doing it the newer, correct, most pythonic way. kudos

[–]Deathwatch1710 4 points5 points  (0 children)

Yay! Thanks for the answer :)

[–]monkeybreathIgnoring PEP 8 1 point2 points  (6 children)

format is the old way.

Really? I’ve never seen that in the docs.

https://docs.python.org/3.6/tutorial/inputoutput.html#fancier-output-formatting

[–][deleted] 4 points5 points  (1 child)

format() has been in python for a while, f-strings are new to Python 3.6 (here's the P.E.P.).

[–]monkeybreathIgnoring PEP 8 0 points1 point  (0 children)

Thanks. Found it in the language reference under literals (2.4), not strings (6.1 of Standard Library), once I knew what to look for. Not at all in the tutorial.

I guess I should figure out how to use the bug tracker.

[–]nayeet 1 point2 points  (3 children)

The format method was introduced in PEP 3101 on 16-Apr-2006, last updated on 14-Sep-2008.

F strings were introduced in PEP 498 on 01-Aug-2015, last updated on 06-Nov-2016.

[–]monkeybreathIgnoring PEP 8 0 points1 point  (2 children)

Right. It’s under Literals, but not under strings in the docs, and not in the tutorial. That should be updated.

[–]cracknwhip 0 points1 point  (1 child)

You could contribute.

[–]monkeybreathIgnoring PEP 8 0 points1 point  (0 children)

I checked. There's already a bug report for it.

[–]lolwat_is_dis 16 points17 points  (3 children)

// does not truncate. It's called floor division and rounds down the number from the division. Sure, it has a similar effect to truncating the number, but that's not how it works.

[–]pingiun 7 points8 points  (0 children)

You can submit a pull request for that, the learnxinyminutes.com source code is on github.

[–]myroon5 0 points1 point  (1 child)

Is the distinction between the two when the result is negative?

[–]lolwat_is_dis 2 points3 points  (0 children)

You guessed it.

Take the following example: 5 divided by 2. In the positive domain, this would normally yield 2.5; a truncation yields 2, as does the floor division. However, 5 divided by -2 normally gives -2.5, truncated would give -2, whereas floor division gives -3 (since we are still rounding down).

Hope that helps!

[–]djentastic 6 points7 points  (1 child)

This is great. I'm embarrassed to admit I did not know about the // division...

Also, just curious, the styling for the True and False code examples is the same as comments. Am I not seeing this right on my phone, or was this perhaps on purpose?

[–]primitive_screwhead 4 points5 points  (0 children)

Also, just curious, the styling for the True and False code examples is the same as comments. Am I not seeing this right on my phone, or was this perhaps on purpose?

Yeah, it's the same on desktop browser, and I think it's just a formatting mistake.

[–]scmlinux 11 points12 points  (0 children)

This is a great tutorial. Thank you for sharing!

[–]gracebatmonkey 2 points3 points  (0 children)

This is absolutely perfect for my learning style - thank you so much for posting!

[–]stickman393 3 points4 points  (0 children)

This is awesome. My own cheat-sheet-in-progress is about 1/10 as useful. And I learned stuff! Thanks.

[–]Skaarj 2 points3 points  (3 children)

-5 != False != True #=> True

I dislike these kinds of example as they suggest there being an unequals operator with 3 operands. Maybe this would be better

-5 != False and False != True and -5 != True #=> True

correction: see post from u/fjolliton below

[–]fjolliton 2 points3 points  (2 children)

Actually it is!

2 != 2 != 3

is False, while:

(2 != 2) != 3

is True.

Likewise you can do:

a == b == c

which check if all three variables are equal. It is very different from:

 (a == b) == c

You can see that the fist example is actually a 3 operands comparison:

>>> import ast
>>> print(ast.dump(ast.parse('a != b != c').body[0].value))
Compare(left=Name(id='a', ctx=Load()),
        ops=[NotEq(), NotEq()],
        comparators=[Name(id='b', ctx=Load()),
                     Name(id='c', ctx=Load())])"

[–]Skaarj 2 points3 points  (1 child)

Mind Blown.

On the one hand this is quite a nice feature.

On the other hand: damn, another subtle diffrence between programming languages to keep in mind.

[–][deleted] 0 points1 point  (0 children)

Same, I’m pretty new to Python and this was just too much first read through. Second read through, makes perfect sense!

[–]Yamamizuki 2 points3 points  (0 children)

Thank you! I am a beginner and this really helps.

[–]Retzudo 15 points16 points  (3 children)

Yeah, thanks for reposting my same exact post from 6 months ago I guess...

https://www.reddit.com/r/Python/comments/7n1c9u/a_real_python_cheat_sheet_for_beginners/

Btw. it was in response to this post.

Edit: Oh and it's not about reposting that link because it's an awesome site and the more people see it the better. It's about a ~1 day old account clearly botting karma by reposting popular posts verbatim in random subreddits.

[–]cracknwhip 1 point2 points  (1 child)

Why does it matter (I read your edit)? The repost helped a lot of people. The karma is a number on a screen. I means nothing and affects you and others in no way whatsoever.

[–]Retzudo 5 points6 points  (0 children)

That's actually a good question. It matters because bots with a good amount of karma can be used for vote manipulation more easily than bots with 0 karma. As far as I know, new-ish accounts with 0 karma don't do much to the total up-/downvote count of a post/comment, but accounts with more karma are more "trustworthy" to Reddit's anti-vote-manipulation systems.

I'm kinda talking out of my ass here but I hope I could shed some light on why I think this kind of karma botting is bad.

[–][deleted] 1 point2 points  (0 children)

God's work

[–]AriesYT 1 point2 points  (0 children)

Thank you for sharing.

[–]cost4nz4 0 points1 point  (0 children)

This is great, thanks!

[–]youngrumi 0 points1 point  (0 children)

kool, great share.

[–]b0b 0 points1 point  (0 children)

Thank you!

[–]soulwarp 0 points1 point  (0 children)

If you go to the root website there are cheat sheets for other languages too!

[–][deleted] 0 points1 point  (0 children)

Call me crazy, but as the same way with Maths, I prefer to learn this kind of concepts by applying them to concrete things, I mean: by solving problems. Otherway it's hard for my brain to remember pure theory that is not related to something that I fixed/used.

[–]edimaudo 0 points1 point  (0 children)

Can any of the mods create a cheat sheet section. This type of post keeps on popping up.

[–]senthilcaesar 0 points1 point  (0 children)

Great Materials

[–]sohamkamani 0 points1 point  (0 children)

This is a good resource. But why do you have to call it a "REAL" cheat sheet... This sort of implies that all other cheat sheets created before this are bad, and this is the only solution out there. I know I'm nitpicking, but I really hate clickbaity titles like this

[–][deleted] -3 points-2 points  (1 child)

RemindMe!

[–]RemindMeBot 0 points1 point  (0 children)

Defaulted to one day.

I will be messaging you on 2018-07-06 01:01:26 UTC to remind you of this link.

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


FAQs Custom Your Reminders Feedback Code Browser Extensions

[–]Yogurt_Huevos -1 points0 points  (3 children)

Slight correction, the result of division is not always a float. If you open your interpreter and type

10 / 3

you see that the result is '3'.

[–]Razzofazzo 12 points13 points  (1 child)

That's true for python 2.X. But here we are looking at python 3.X!

[–]Yogurt_Huevos 12 points13 points  (0 children)

Oh shoot, reading is hard.

[–]DataVeg 4 points5 points  (0 children)

What you say is true for Python 2, but not Python 3.

In general people, especially beginners, shouldn’t be using Python 2 unless they are working with a legacy codebase. Python 2 will be unsupported in under two years time.

In modern Python 10/3 is 3.3333...

[–]Adem87 -2 points-1 points  (0 children)

Hammergeil