W3Schools Learner's Blog

W3Schools Programming knowledge summary website

div

12/20/2021

Python Data Types

 A data type defines the type of a variable. Since everything is an object in Python, data types are actually classes; and the variables are instances of the classes.

In any programming language, different operations can be performed over different types of data types some of which are common with other datatypes while some can be very specific to that particular datatype.

1. Built-in Data Types in Python

Python has the following data types built-in by default.

Category
Data types / Class names
Text/String
Numeric
intfloatcomplex
List
listtuplerange
Map
dict
Set
setfrozenset
Boolean
bool
Binary
bytesbytearraymemoryview

2. Data Types in Detail

2.1. str

The string can be defined as the sequence of characters enclosed in single, double, or triple quotes. The triple quotes (“””) can be used for writing multi-line strings.

str data type
x = 'A'
y = "B"
z = """
    C
    """
 
print(x)    # prints A
print(y)    # prints B
print(z)    # prints C
 
print(x + y)    # prints AB - concatenation
 
print(x*2)      # prints AA - repeatition operator
 
name = str('john'# Constructor
 
sumOfItems = str(100)   # type conversion from int to string

2.2. int, float, complex

These are number types. They are created when a number is assigned to a variable.

  • int holds signed integers of non-limited length.
  • float holds floating precision numbers and they are accurate upto 15 decimal places.
  • complex – A complex number contains the real and imaginary part.
numeric types
x = 2                   # int
x = int(2)              # int  
 
x = 2.5                 # float
x = float(2.5)          # float
 
x = 100+3j              # complex
x = complex(100+3j)     # complex

2.3. list, tuple, range

In Python, list is an ordered sequence of some data written using square brackets([ ]) and commas(,). A list can contain data of different types.

Slice [:] operator can be used to access the data in the list.

The concatenation operator (+) and repetition operator (*) works similar the str data type.

range can be considered as sublist, taken out of a list using slicing operator.

tuple is similar to the list – except tuple is a read-only data structure and we can’t modify the size and value of the items of a tuple. Also, items are enclosed in parentheses (, ).

list types
randomList = [1, "one", 2, "two"]
print (randomList);                 # prints [1, 'one', 2, 'two']
print (randomList + randomList);    # prints [1, 'one', 2, 'two', 1, 'one', 2, 'two']
print (randomList * 2);             # prints [1, 'one', 2, 'two', 1, 'one', 2, 'two']
 
alphabets  = ["a", "b", "c", "d", "e", "f", "g", "h"
 
print (alphabets[3:]);              # range - prints ['d', 'e', 'f', 'g', 'h']
print (alphabets[0:2]);             # range - prints ['a', 'b']
 
randomTuple = (1, "one", 2, "two")
print (randomTuple[0:2]);           # range - prints (1, 'one')
 
randomTuple[0] = 0      # TypeError: 'tuple' object does not support item assignment

2.4. dict

dict or dictionary is an ordered set of a key-value pair of items. A key can hold any primitive data type whereas value is an arbitrary Python object.

The entries in the dictionary are separated with the comma and enclosed in the curly braces {, }.

dict types
charsMap = {1:'a', 2:'b', 3:'c', 4:'d'};  
 
print (charsMap);       # prints {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
print("1st entry is " + charsMap[1]);  # prints 1st entry is a
print (charsMap.keys());        # prints dict_keys([1, 2, 3, 4])
print (charsMap.values());      # prints dict_values(['a', 'b', 'c', 'd'])

2.5. set, frozenset

The set in python can be defined as the unordered collection of various items enclosed within the curly braces{, }.

The elements of the set can not be duplicate. The elements of the python set must be immutable.

Unlike list, there is no index for set elements. It means we can only loop through the elements of the set.

The frozen sets are the immutable form of the normal sets. It means we cannot remove or add any item into the frozen set.

set types
digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}  
 
print(digits)           # prints {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
 
print(type(digits))     # prints <class 'set'>
 
print("looping through the set elements ... "
for i in digits: 
    print(i)            # prints 0 1 2 3 4 5 6 7 8 9 in new lines
 
digits.remove(0)    # allowed in normal set
 
print(digits)       # {1, 2, 3, 4, 5, 6, 7, 8, 9}
 
frozenSetOfDigits = frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})  
 
frozenSetOfDigits.remove(0) # AttributeError: 'frozenset' object has no attribute 'remove'

2.6. bool

bool values are the two constant objects False and True. They are used to represent truth values. In numeric contexts, they behave like the integers 0 and 1, respectively.

x = True
y = False
 
print(x)    #True
print(y)    #False
 
print(bool(1))  #True
print(bool(0))  #False

2.7. bytes, bytearray, memoryview

bytes and bytearray are used for manipulating binary data. The memoryview uses the buffer protocol to access the memory of other binary objects without needing to make a copy.

Bytes objects are immutable sequences of single bytes. We should use them only when working with ASCII compatible data.

The syntax for bytes literals is same as string literals, except that a 'b' prefix is added.

bytearray objects are always created by calling the constructor bytearray(). These are mutable objects.

bytes, memoryview types
x = b'char_data'
x = b"char_data"
 
y = bytearray(5)
 
z = memoryview(bytes(5))
 
print(x)    # b'char_data'
print(y)    # bytearray(b'\x00\x00\x00\x00\x00')
print(z)    # <memory at 0x014CE328>

3. type() function

The type() function can be used to get the data type of any object.

Get type
x = 5
print(type(x))          # <class 'int'>
 
y = 'howtodoinjava.com'
print(type(y))          # <class 'str'>

Drop me your questions in comments.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.