1  Data Types

Knowing about data types in Python is crucial for several reasons:

Overall, having knowledge of data types in Python enables you to write robust, efficient, and understandable code that operates correctly with the data it handles. It empowers you to make informed decisions about memory usage, data manipulation, input validation, and code integration, leading to better overall programming proficiency.

Scalar Types

Python has a small set of built-in types for handling numerical data, strings, Boolean (True or False) values, and dates and time. These “single value” types are sometimes called scalar types, and we refer to them in this book as scalars . See Standard Python scalar types for a list of the main scalar types. Date and time handling will be discussed separately, as these are provided by the datetime module in the standard library.

?(caption)

Standard Python scalar types
Type
Description
None
The Python “null” value (only one instance of the None object exists)
str
String type; holds Unicode strings
bytes
Raw binary data
float
Double-precision floating-point number (note there is no separate double type)
bool
A Boolean True or False value
int
Arbitrary precision integer
x = 5
type(x)
int
y=7.5
type(y)
float
type(x+y)
float

Numeric Type

The primary Python types for numbers are int and float. An int can store arbitrarily large numbers:

ival = 17239871
ival ** 6
26254519291092456596965462913230729701102721

Booleans

can take only two values: True and False.

print(4 == 5)
print(4 < 5)
b = 4 != 5
print(b)
print(int(b))
False
True
True
1

Strings

Many people use Python for its built-in string handling capabilities. You can write string literals using either single quotes or double quotes (double quotes are generally favored):

a = 'one way of writing a string'
b = "another way"

type(a)
str

For multiline strings with line breaks, you can use triple quotes, either ''' or """:

c = """
This is a longer string that
spans multiple lines
"""
c.count("\n")
3

Strings built-in methods

Note: All string methods return new values. They do not change the original string.

Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it was found
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it was found
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Converts the elements of an iterable into a string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where it was found
rindex() Searches the string for a specified value and returns the last position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning

Methods

Many operations/functions in python are specific to the data type even though we use the same syntax:

print(x+y)
print(a+b)
12.5
one way of writing a stringanother way

Type conversion

We can often convert from one type to another if it makes sense:

str(x)
'5'
float(x)
5.0

Immutable Objects

Mutable objects are those that allow you to change their value or data in place without affecting the object’s identity. In contrast, immutable objects don’t allow this kind of operation. You’ll just have the option of creating new objects of the same type with different values.

In Python, mutability is a characteristic that may profoundly influence your decision when choosing which data type to use in solving a given programming problem. Therefore, you need to know how mutable and immutable objects work in Python.

In Python, variables don’t have an associated type or size, as they’re labels attached to objects in memory. They point to the memory position where concrete objects live. In other words, a Python variable is a name that refers to or holds a reference to a concrete object. In contrast, Python objects are concrete pieces of information that live in specific memory positions on your computer.

The main takeaway here is that variables and objects are two different animals in Python:

  • Variables hold references to objects.
  • Objects live in concrete memory positions.

Read more about this topic

Strings and tuples are immutable:

a = "this is a string"

a[10] = "f"
TypeError: 'str' object does not support item assignment

Tuples

A tuple is a fixed-length, immutable sequence of Python objects which, once assigned, cannot be changed. The easiest way to create one is with a comma-separated sequence of values wrapped in parentheses:

tup = (4, 5, 6)
print(tup)
tup = (4, "Ray", 6)
print(tup)
#In many contexts, the parentheses can be omitted
tup = 4, "Ray", 6
print(tup)
(4, 5, 6)
(4, 'Ray', 6)
(4, 'Ray', 6)

Elements can be accessed with square brackets [] as with most other sequence types. As in C, C++, Java, and many other languages, sequences are 0-indexed in Python:

tup[0]
4
#but you cannot change the value:
tup[0] = 3
TypeError: 'tuple' object does not support item assignment

You can concatenate tuples using the + operator to produce longer tuples:

(4, None, 'foo') + (6, 0) + ('bar',)
(4, None, 'foo', 6, 0, 'bar')

Multiplying a tuple by an integer, as with lists, has the effect of concatenating that many copies of the tuple:

('foo', 'bar') * 4
('foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'bar')

Unpacking tuples

If you try to assign to a tuple-like expression of variables, Python will attempt to unpack the value on the righthand side of the equals sign:

tup = (4, 5, 6)
a, b, c = tup