Python For Rubyists, Part II: Data Types
Welcome back to this learn-quick series for Rubyists looking to learn Python! In case you missed it, you can check out Part I here.
Next up: Data Types.
Like most programming languages, Python has a few basic data types built in. Like in Ruby, you have strings, integers, and floats.
To convert between them, you can use the
float() functions. For example:
Here, we assigned the string
"3" to the variable
x. Then we converted it to an integer using
int(). Then we converted it to a float using
float() and reassigned the resulting value to
x. Finally, we converted that float value back to a string using
Python also has Booleans, although the values are styled
It’s also worth noting that what was
nil in Ruby is
None in Python.
Now come the bigger differences. Where in Ruby you have arrays and hashes, in Python you have lists and dictionaries.
… and tuples and sets.
Lists work similarly to arrays, although there are special ways to create and modify them known as list comprehensions that we’ll get into in a later post.
Dictionaries work similarly to hashes — you can assign keys to values, map over them, etc. The syntax uses colons (which also works with Ruby 2.0 and later); Ruby’s hash rocket will get you nowhere here.
Tuples, meanwhile, are a bit more specialized. They’re sort of like an array or list in the sense that they consist of multiple items in an order.
However, they’re completely immutable. Once you create a tuple, you can access the information inside it, but you cannot change it in any way.
You create a tuple by listing its elements inside a pair of parentheses, like so:
The final data type we’ll cover in this post is the set. Again, this data type can contain multiple items (in this case, in curly braces), but the elements are unordered and remain unique.
You can use sets for all kinds of things, especially math. You can get the difference between two sets, you can add them together, you can find all the elements they have in common — but you can’t have an element multiple times or access an element by any kind of index.
Notice that the elements in the states set are in no particular order, and that when we try to add “Alaska” for a second time, the set remains unchanged.
That’s all for now! Check back for Part III, where we’ll look at conditionals.