Python Datatypes
Python Datatypes
Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object
in Python programming, data types are actually classes and variables are instances (object) of
these classes. The following are the standard or built-in data types in Python
A list can
Python List reverse(): # create a list of prime numbers Syntax of List reverse()
The reverse() method prime_numbers = [2, 3, 5, 7] The syntax of the reverse()
reverses the elements of method is:
the list. # reverse the order of list elements list.reverse()
prime_numbers.reverse()
reverse() parameter
The reverse() method doesn't
print('Reversed List:', take any arguments.
prime_numbers)
# Output: Reversed List: [7, 5, 3, 2]
Python List sort(): prime_numbers = [11, 3, 7, 5, 2] sort() Syntax
The sort() method sorts the The syntax of the sort()
items of a list in ascending # sorting the list in ascending order method is:
or descending order. prime_numbers.sort() list.sort(key=..., reverse=...)
sort() Parameters
print(prime_numbers) By default, sort() doesn't
require any extra parameters.
# Output: [2, 3, 5, 7, 11] However, it has two optional
parameters:
reverse - If True, the
sorted list is reversed
(or sorted in
Descending order)
key - function that
serves as a key for the
sort comparison
If you simply use :, you will get all the elements of the list. This is similar to
print(my_list).
Get all the Items After a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:])
Output
[3, 4, 5]
If you want to get all the elements after a specific index, you can mention that index
before : as shown in example above.
In the above example, elements at index 2 and all the elements after index 2 are printed.
Note: indexing starts from 0. Item on index 2 is also included.
Get all the Items Before a Specific Position
my_list = [1, 2, 3, 4, 5]
print(my_list[:2])
Output
[1, 2]
This example lets you get all the elements before a specific index. Mention that index
after :.
In the example, the items before index 2 are sliced. Item on index 2 is excluded.
Get all the Items from One Position to Another Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Output
[3, 4]
If you want to get all the elements between two specific indices, you can mention them
before and after :.
In the above example, my_list[2:4] gives the elements between 2nd and the 4th positions. The
starting position (i.e. 2) is included and the ending position (i.e. 4) is excluded.
If you want the indexing to start from the last item, you can use negative sign -.
my_list = [1, 2, 3, 4, 5]
print(my_list[::-2])
Output
[5, 3, 1]
The items at interval 2 starting from the last index are sliced.
If you want the items from one position to another, you can mention them from start to stop.
my_list = [1, 2, 3, 4, 5]
print(my_list[1:4:2])
Output
[2, 4]
The items from index 1 to 4 are sliced with intervals of 2.
String
A String is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change it.
Strings are used widely in many different applications, such as storing and manipulating text
data, representing names, addresses, and other types of data that can be represented as text.
In Python, Strings are arrays of bytes representing Unicode characters. However, Python does
not have a character data type, a single character is simply a string with a length of “1”.
Square brackets [ ] can be used to access elements of the string.
Function Description Parameters Example
len() Returns the None len("Hello, World!")
length of a
string.
str() Converts an None str(42)
object to a
string.
+ Concatenates Strings to "Hello" + " " + "World!"
two or more concatenate
strings.
* Repeats a Number of "Hello" * 3
string repetitions
multiple
times.
upper() Converts a None "hello".upper()
string to
uppercase.
lower() Converts a None "Hello".lower()
string to
lowercase.
capitalize( Capitalizes None "hello world".capitalize()
)
the first
character of
a string.
title() Capitalizes None "hello world".title()
the first
character of
each word in
a string.
strip() Removes None " hello ".strip()
leading and
trailing
whitespace
from a
string.
lstrip() Removes None " hello ".lstrip()
leading
whitespace
from a
string.
rstrip() Removes None " hello ".rstrip()
trailing
whitespace
from a
string.
replace() Replaces all old "Hello, World".replace("World",
(substring to "Python")
occurrences
of a replace), new
substring (replacement
with another substring)
substring.
split() Splits a delimiter "apple,banana,cherry".split(",")
string into a (optional,
list of default is
substrings whitespace)
based on a
delimiter.
join() Joins a list of iterable ",".join(["apple", "banana",
(list of "cherry"])
strings into a
single string strings to
using a join)
delimiter.
find() Searches for substring "Hello, World".find("World")
a substring (substring to
within a find)
string and
returns the
index of the
first
occurrence
(or -1 if not
found).
index() Searches for substring "Hello, World".index("World")
a substring (substring to
within a find)
string and
returns the
index of the
first
occurrence
(raises an
exception if
not found).
count() Counts the substring "hello world hello".count("hello")
number of (substring to
non- count)
overlapping
occurrences
of a
substring in a
string.
startswith( Checks if a prefix "Hello, World".startswith("Hello")
) (prefix to
string starts
with a check)
specified
prefix.
endswith() Checks if a suffix "Hello, World".endswith("World")
string ends (suffix to
with a check)
specified
suffix.
isdigit() Checks if a None "12345".isdigit()
string
contains only
digits.
isalpha() Checks if a None "Hello".isalpha()
string
contains only
alphabetic
characters.
isalnum() Checks if a None "Hello123".isalnum()
string
contains only
alphanumeri
c characters.
islower() Checks if all None "hello".islower()
characters in
a string are
lowercase.
isupper() Checks if all None "HELLO".isupper()
characters in
a string are
uppercase.
isspace() Checks if a None " ".isspace()
string
contains only
whitespace
characters.
swapcase() Swaps the None "Hello, World!".swapcase()
case of
characters in
a string.
center() Centers a width (total "Hello".center(10, "-")
string within width),
a specified fillchar
width, (optional,
padding with default is
a specified space)
character.
zfill() Pads a width (total "42".zfill(5)
numeric width)
string with
zeros on the
left to a
specified
width.
rjust() Right-aligns width (total "Hello".rjust(10, "-")
a string width),
within a fillchar
specified (optional,
width, default is
padding with space)
a specified
character.
ljust() Left-aligns a width (total "Hello".ljust(10, "-")
string within width),
a specified fillchar
width, (optional,
padding with default is
a specified space)
character.
rfind() Searches for substring "Hello, World".rfind("World")
a substring (substring to
within a find)
string and
returns the
index of the
last
occurrence
(or -1 if not
found).
rindex() Searches for substring "Hello, World".rindex("World")
a substring (substring to
within a find)
string and
returns the
index of the
last
occurrence
(raises an
exception if
not found).
rstrip() Removes None " hello ".rstrip()
trailing
whitespace
from a
string.
lstrip() Removes None " hello ".lstrip()
leading
whitespace
from a
string.
maketrans() Creates a x (characters str.maketrans("abc", "123")
translation to replace), y
table for use (characters to
with replace with)
translate(
) to replace
specified
characters.
translate() Translates a table "abc".translate(str.maketrans("abc
(translation ", "123"))
string by
applying a table created
translation by
maketrans(
table created
with ))
maketrans(
).
partition() Splits a separator "apple,banana,cherry".partition(",
(separator to ")
string into
three parts split the
based on a string)
specified
separator and
returns a
tuple.
rpartition( Splits a separator "apple,banana,cherry".rpartition("
) (separator to ,")
string into
three parts split the
from the string)
right based
on a
specified
separator and
returns a
tuple.
isnumeric() Checks if a None `"3455".isnumeric()
string
contains only
numeric
characters
(including
digits from
other
scripts).