0% found this document useful (0 votes)
15 views

Python Datatypes

Python data types include numeric, sequence, set and dictionary types. Numeric types store integer and floating point numbers, sequence types include strings, lists and tuples which store ordered collections of values, sets store unordered collections of unique elements and dictionaries store key-value pairs.

Uploaded by

balaeduc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Datatypes

Python data types include numeric, sequence, set and dictionary types. Numeric types store integer and floating point numbers, sequence types include strings, lists and tuples which store ordered collections of values, sets store unordered collections of unique elements and dictionaries store key-value pairs.

Uploaded by

balaeduc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

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

Numeric Data Type in Python


The numeric data type in Python represents the data that has a numeric value. A numeric
value can be an integer, a floating number, or even a complex number. These values are
defined as Python int, Python float, and Python complex classes in Python.
 Integers – This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how
long an integer value can be.
 Float – This value is represented by the float class. It is a real number with a floating-
point representation. It is specified by a decimal point. Optionally, the character e or E
followed by a positive or negative integer may be appended to specify scientific
notation.
 Complex Numbers – Complex number is represented by a complex class. It is
specified as (real part) + (imaginary part)j. For example – 2+3j

Sequence Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python:
 Python String: Strings in Python are arrays of bytes representing Unicode characters. A
string is a collection of one or more characters put in a single quote, double-quote, or triple-
quote. In python there is no character data type, a character is a string of length one. It is
represented by str class.
 Python List: Lists are just like arrays, declared in other languages which is an
ordered collection of data. It is very flexible as the items in a list do not need to be of
the same type.
 Python Tuple: Just like a list, a tuple is also an ordered collection of Python objects.
The only difference between a tuple and a list is that tuples are immutable i.e. tuples
cannot be modified after it is created. It is represented by a tuple class.

Set Data Type in Python


In Python, a Set is an unordered collection of data types that is iterable, mutable and has no
duplicate elements. The order of elements in a set is undefined though it may consist of
various elements.

Dictionary Data Type in Python


A dictionary in Python is an unordered collection of data values, used to store data values like
a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds
a key: value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon : , whereas each key is separated by a
‘comma’.
Python Data Structures
List

A list can

 store elements of different types (integer, float, string, etc.)


 store duplicate elements

Python List Methods

Methods Example Syntax


Python List index(): Code: list.index(element, start,
The index() method animals = ['cat', 'dog', 'rabbit', end)
returns the index of the 'horse'] list index() parameters
specified element in the The list index() method can
list. # get the index of 'dog' take a maximum of three
index = animals.index('dog') arguments:
 element - the
print(index) element to be
searched
# Output: 1  start (optional) -
start searching from
this index
 end (optional) -
search the element
up to this index

Python List append(): currencies = ['Dollar', 'Euro', Syntax of List append()


The append() method 'Pound'] The syntax of the append()
adds an item to the end of method is:
the list. # append 'Yen' to the list list.append(item)
currencies.append('Yen')
append() Parameters
print(currencies) The method takes a single
argument
# Output: ['Dollar', 'Euro',  item - an item
'Pound', 'Yen'] (number, string, list
etc.) to be added at
the end of the list

Python List extend(): # create a list Syntax of List extend()


The extend() method adds prime_numbers = [2, 3, 5]
all the elements of an The syntax of the extend()
iterable (list, tuple, string # create another list method is:
etc.) to the end of the list. numbers = [1, 4]
list1.extend(iterable)
# add all elements of
prime_numbers to numbers
numbers.extend(prime_numbers) Here, all the elements of
iterable are added to the
end of list1.
print('List after extend():',
numbers)

# Output: List after extend(): [1, extend() Parameters


4, 2, 3, 5]
As mentioned, the extend()
method takes an iterable
such as list, tuple, string
etc.

Python List insert(): # create a list of vowels Syntax of List insert()


The insert() method vowel = ['a', 'e', 'i', 'u'] The syntax of the insert()
inserts an element to the method is
list at the specified index. # 'o' is inserted at index 3 (4th list.insert(i, elem)
position) Here, elem is inserted to the
vowel.insert(3, 'o') list at the ith index. All the
elements after elem are
shifted to the right.
print('List:', vowel)
insert() Parameters
# Output: List: ['a', 'e', 'i', 'o', 'u'] The insert() method takes
two parameters:
 index - the index
where the element
needs to be inserted
 element - this is the
element to be
inserted in the list

Python List remove(): # create a list Syntax of List remove()


The remove() method prime_numbers = [2, 3, 5, 7, 9, 11]
removes the first matching The syntax of the remove()
element (which is passed as # remove 9 from the list method is:
an argument) from the list. prime_numbers.remove(9)
list.remove(element)

# Updated prime_numbers List


print('Updated List: ', remove() Parameters
prime_numbers)
 The remove()
# Output: Updated List: [2, 3, 5, 7, method takes a
11] single element as an
argument and
removes it from the
list.
 If the element
doesn't exist, it
throws ValueError:
list.remove(x): x not
in list exception.

Python List count(): # create a list Syntax of List count()


The count() method returns numbers = [2, 3, 5, 2, 11, 2, 7] The syntax of the count()
the number of times the method is:
specified element appears # check the count of 2 list.count(element)
in the list. count = numbers.count(2)
count() Parameters
The count() method takes a
print('Count of 2:', count) single argument:
 element - the
# Output: Count of 2: 3 element to be
counted

Python List pop(): Syntax of List pop()


The list pop() method prime_numbers = [2, 3, 5, 7] The syntax of the pop()
removes the item at the method is:
specified index. The method # remove the element at index 2 list.pop(index)
also returns the removed removed_element =
item. prime_numbers.pop(2) pop() parameters
 The pop() method
print('Removed Element:', takes a single
removed_element) argument (index).
print('Updated List:',  The argument passed
prime_numbers) to the method is
optional. If not
# Output: passed, the default
# Removed Element: 5 index -1 is passed as
# Updated List: [2, 3, 7] an argument (index
of the last item).
 If the index passed to
the method is not in
range, it throws
IndexError: pop index
out of range
exception.

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

Python List copy(): # mixed list copy() Syntax


The copy() method returns prime_numbers = [2, 3, 5] The syntax of the copy()
a shallow copy of the list. method is:
# copying a list new_list = list.copy()
numbers = prime_numbers.copy()
copy() Parameters
The copy() method doesn't
print('Copied List:', numbers) take any parameters.

# Output: Copied List: [2, 3, 5]


Python List clear(): prime_numbers = [2, 3, 5, 7, 9, 11] Syntax of List clear()
The clear() method removes The syntax of clear() method
all items from the list. # remove all elements is:
prime_numbers.clear() list.clear()

# Updated prime_numbers List clear() Parameters


print('List after clear():', The clear() method doesn't
prime_numbers) take any parameters.

# Output: List after clear(): []


Slice Lists
To understand this example, you should have the knowledge of the following Python
programming topics:
The format for list slicing is [start:stop:step]:
start is the index of the list where slicing starts.
stop is the index of the list where slicing ends.
step allows you to select nth item within the range start to stop.

List slicing works similar to Python slice() function.


Get all the Items
my_list = [1, 2, 3, 4, 5]
print(my_list[:])
Output
[1, 2, 3, 4, 5]

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.

Get the Items at Specified Intervals


my_list = [1, 2, 3, 4, 5]
print(my_list[::2])
Output
[1, 3, 5]
If you want to get elements at specified intervals, you can do it by using two :.
In the above example, the items at interval 2 starting from index 0 are sliced.

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).

You might also like