0% found this document useful (0 votes)
4 views11 pages

1DATA TYPES AND EXPRESSIONS IN PYTHON Short Cuts

The document provides an overview of data types in Python, including Numbers, Strings, Boolean, List, Tuple, Set, and Dictionary. Each data type is explained with definitions, examples, and code snippets demonstrating their usage and characteristics. Key concepts such as mutability, immutability, and operations like concatenation and slicing are also covered.

Uploaded by

Anamika Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views11 pages

1DATA TYPES AND EXPRESSIONS IN PYTHON Short Cuts

The document provides an overview of data types in Python, including Numbers, Strings, Boolean, List, Tuple, Set, and Dictionary. Each data type is explained with definitions, examples, and code snippets demonstrating their usage and characteristics. Key concepts such as mutability, immutability, and operations like concatenation and slicing are also covered.

Uploaded by

Anamika Singh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

DATA TYPES AND EXPRESSIONS IN PYTHON

DATA TYPES

The major data types defined in Python are:

● Numbers

● Strings

● Boolean

● List

● Tuple

● Set

● Dictionary

Numbers - The three numeric data types defined are integer, floating point number and complex number.

Integer, as we all know, is a whole number and does not contain decimal points. It can be positive or
negative.

Fractional numbers or numbers with decimal points are called floating point numbers in programming
languages. Such floating point numbers contain a decimal part and a fractional part. A floating point number
has an accuracy of up to 15 decimal places.

Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary part.

complex_number=complex(3,4)
print(complex_number)
c=3+8j
print(c)
print(c.real)
print(c.imag)

Output
(3+4j)
(3+8j)
3.0
8.0
>>>complex(3,4)
(3+4j)
>>>c=3+8j
>>>c.real
3.0
>>>c.imag
8.0

The type() is a built-in function to find the data type of a variable.

a=12.345
b=3
c=3+4j
print("Type of a:",type(a))
print("Type of b:",type(b))
print("Type of c:",type(c))

OUTPUT:

Type of a: <class 'float'>


Type of b: <class 'int'>
Type of c: <class 'complex'>

STRINGS - String is a collection of one or more characters which consists of letters, numbers, symbols or
any other type of characters, including spaces string can be enclosed in single quotes or double quotes or triple
quotes.

print('Have a nice day')


print("Have a nice day")
print('good', 'morning')
print("good","morning")

OUTPUT:

Have a nice day


Have a nice day
good morning
good morning

Strings cannot be modified or changed, i.e, they are immutable. Once a string is created we cannot modify
the string.
Code

str="hello"
print(len(str))
print(str[0])
print(str[1])

Output

5
h
e

Code

str="hello"
print(str)
print(len(str))
print(str[0])
print(str[1])
str[0]="x"

Output

5
h
e
Traceback (most recent call last):
File "C:/Users/hp/OneDrive/Pictures/string1.py", line 5, in <module>
str[0]="x"
TypeError: 'str' object does not support item assignment

BOOLEAN - In Python, Boolean variables can have 2 values: True or False, both of which are keywords.
As Python is case-sensitive, T and F should be in upper case.

>>> 5==5 >>> 5==6


True False
a=5
print(a==5)
print(a==6)

Output

True
False

LIST - List, like an array, contains the same (or different) type of items and is a very commonly used data type
in Python. A list is an ordered sequence where each element can be addressed using the corresponding index
value. A list is created by enclosing all the elements in a square bracket and separating each element with a
comma.

Code 1

mylist1=["sun" ,"moon","stars"]
print(mylist1)
print(len(mylist1))

The output would be:

['sun', 'moon', 'star']


3

Code 2

mylist2 = [1, 2, 3, 10, 20.5, 50.5, "stars"]


print(mylist2)

The output would be:

[1, 2, 3, 10, 20.5, 50.5, 'stars']

Each element in a list has an index and starts with a 0.if there are n elements, the index is from 0 to n-1 and the
m'th element in the list has index m-1.

Code
mylist1 = ["sun", "moon", "stars"]
print("In mylist1, At index 0:", mylist1[0])
print("In mylist1, At index 2:", mylist1[2])
mylist2 = [1, 2, 3, 4, 8.85, 9.25]
print("In mylist2, At index 0:", mylist2[0])
print("In mylist2, At index 5:", mylist2[5])

The output would be:

In mylist1, At index 0: sun


In mylist1, At index 2: stars
In mylist2, At index 0: 1
In mylist2, At index 5: 9.25

There are three operations that can be performed easily with strings or lists: Concatenation, repetition and for
making sub-lists.
Slicing literally slices a part of the list and forms a subset of the whole list. Concatenation is used to combine
two or more lists.
Repetition, as the word suggests, repeats the same list again or a specified number of times. They are done using
plus (+), asterisk (*) and slicing [:] operators respectively.

CONCATENATION (Using + operator )

mylist1 = ["sun", "moon", "star"]


mylist2 = [1, 2, 3, 10, 20.5, 50.5, "stars"]
editlist = mylist1 + mylist2
print(editlist)

Output combines all elements from mylist1 and mylist2 into a single list, retaining their original order.

['sun', 'moon', 'star', 1, 2, 3, 10, 20.5, 50.5, 'stars']

REPETITION (Using * operator )

A string is repeated any number of times using * operator.


mylist1 is repeated again by writing 2*mylist1.
It can also be written as mylist1*2.

Code

mylistl = ["sun", "moon", "stars"]


replist1 = 2 * mylistl
print(replist1)
Output

['sun', 'moon', 'stars', 'sun', 'moon', 'stars']

both concatenation and repetition are performed using + and * operators respectively.

Code

mylistl = ["sun", "moon", "stars"]


mylist2 = [1, 2, 3, 4, 8.85, 9.25]
newlist = 3 * mylistl + mylist2
print(newlist)

Output

['sun', 'moon', 'stars', 'sun', 'moon', 'stars', 'sun', 'moon', 'stars', 1, 2, 3, 4, 8.85, 9.25]

LIST IS MUTABLE

mylist = ["sun", "moon", 1,5,10,100]


mytuple = ("sun", "moon", 1,5,10,100)
mylist[1]="stars"
mylist[5]=300
print("List is: ",mylist)

The output for the given code will be as follows:

List is: ['sun', 'stars', 1, 5, 10, 300]

SLICING OR MAKING SUB-LISTS

SYNTAX: list_name[startindex :endindex: interval] #interval is optional

In slicing, we can take a part of the whole list, by specifying from which index to which index, hence the name
slicing. We can take a slice of the list. There is an option to give interval or step also. If we give 2 as step or
interval, only alternate elements will be taken. Another thing to be noted is that the value at endindex will not be
printed. Only the value just before that will be printed.

Code
numlist = [1,2.5,3,6,8.85,9.25,100,200,300]
slicel = numlist[0:4]
print(slicel)
slice2 = numlist[2:5]
print(slice2)
slice3 = numlist[4:5]
print(slice3)
slice4 = numlist[4:2]
print(slice4)

Output

[1, 2.5, 3, 6]
[3, 6, 8.85]
[8.85]
[]

Explanation

# Initial list
numlist = [1, 2.5, 3, 6, 8.85, 9.25, 100, 200, 300]

# Slicing from index 0 to 3 (exclusive of 4)


slicel = numlist[0:4]
print(slice1) # Output: [1, 2.5, 3, 6]

# Slicing from index 2 to 4 (exclusive of 5)


slice2 = numlist[2:5]
print(slice2) # Output: [3, 6, 8.85]

# Slicing from index 4 to 4 (exclusive of 5)


slice3 = numlist[4:5]
print(slice3) # Output: [8.85]

# Slicing from index 4 to 2 (slicing does not work in reverse order)


slice4 = numlist[4:2]
print(slice4) # Output: []
Code

numlist1 = [1, 2.5, 3, 6, 8.85, 9.25, 20, 30, 40, 50, 100, 200, 300, 400, 500, 600, "hello", "bye"]
slice1 = numlist1[0:6:2]
print(slice1)
slice2 = numlist1[0:7:2]
print(slice2)
slice3 = numlist1[1:9:3]
print(slice3)
slice4 = numlist1[0:18:3]
print(slice4)

Output

[1, 3, 8.85]
[1, 3, 8.85, 20]
[2.5, 8.85, 30]
[1, 6, 20, 50, 300, 600]

In the first example (slice1), numlist1 [0:6:2] means it takes elements from numlist1[0] to numlist1 [5], but
skipping 1 element in between the selected range of elements. You can see in the output that numlist1[0],
numlist1[2], numlist1[4] are printed.

In the second example (slice2), numlist1 [0:7:2] means it takes elements from numlist1 [0] to numlist1[6], but
skipping 1 element in between the selected range of elements. You can see in the output that numlist1 [0],
numlist1 [2], numlist1 [4] and numlist1[6] are printed.

In the third example (slice3), numlist1 [1:9:3] means it takes elements from numlist1 [1] skips those at index 2
and 3, then takes numlist1 [4], skips those at 5 and 6, then takes numlist1 [7], then skipping numlist1[8] and it
ends, thus printing 3 elements.

In the fourth example (slice4), numlist1 [0:18:3] means it takes elements from numlist1 [0] to numlist1 [17], all
elements are taken with an interval of 3. Skipping 2 elements in between. Thus, it prints numlist1 [0], numlist1
[3], numlist1 [6], numlist1 [9], numlist1 [12] and numlist1 [15] in the new slice.

Tuple

Tuple is a set of data items, very similar to lists. A built-in data types that lets us create immutable sequence of
values.The main differences between the two are:

1. Elements are enclosed in square brackets([]) in lists, whereas in tuple, the items are enclosed in
parentheses (()).
2. Second difference is in their mutability. Lists are mutable, so they can be changed or new members can be
added. But tuple is a read-only list which is not mutable. It cannot be changed, if items are stored once.

Code

mylist = ["sun", "moon", 1,5,10,100]


mytuple = ("sun", "moon", 1,5,10,100)
print("List is: ",mylist)
print("Tuple is: ",mytuple)
print(type(mylist))
print(type(mytuple))
print(len(mytuple))
print(mytuple[0])
print(mytuple[1])
print(mytuple[2])

Output
List is: ['sun', 'moon', 1, 5, 10, 100]
Tuple is: ('sun', 'moon', 1, 5, 10, 100)
<class 'list'>
<class 'tuple'>
6
sun
moon
1

Tuple is not mutable

mylist = ["sun", "moon", 1,5,10,100]


mytuple = ("sun", "moon", 1,5,10,100)
print("List is: ",mylist)
print("Tuple is: ",mytuple)
print(type(mylist))
print(type(mytuple))
print(len(mytuple))
print(mytuple[0])
print(mytuple[1])
print(mytuple[2])
mytuple[0]=5

NOTE: The data items in a tuple cannot be modified and therefore, tuple is not mutable. The
data items in a list can be modified any time. Therefore, list is mutable.
Output

List is: ['sun', 'moon', 1, 5, 10, 100]


Tuple is: ('sun', 'moon', 1, 5, 10, 100)
<class 'list'>
<class 'tuple'>
6
sun
moon
1
Traceback (most recent call last):
File "C:/Users/hp/OneDrive/Pictures/tuple1.py", line 11, in <module>
mytuple[0]=5
TypeError: 'tuple' object does not support item assignment

Dictionary

Dictionary consists of a collection of key-value pairs or dictionaries are used to store data values in key:
value pairs .
Just like in lists, it is a collection of data elements. But the difference is that instead of the value it has a
key which can be used to access the value. Thus, Element in the dictionary comes as a key-value pair.
Each key is mapped to its associated value when we define a key-value pair. You can define a dictionary
by enclosing a comma-separated list of key-value pairs in curly braces {}.
A colon: separates each key from its associated value:
To get the value corresponding to a key in the dictionary, we can use, dictionaryname.get(<key>).

dictionaryname.values() will print all the values in the dictionary and dictionaryname.keys() will
print all the keys in the dictionary.

Code
dict={"name":"ayush",
"cgpa":85,
"marks":[87,77,90]}
print(dict)
print(type(dict))
print(len(dict))
print(dict.get("marks"))
print(dict.values())
print(dict.keys())

Output
{'name': 'ayush', 'cgpa': 85, 'marks': [87, 77, 90]}
<class 'dict'>
3
[87, 77, 90]
dict_values(['ayush', 85, [87, 77, 90]])
dict_keys(['name', 'cgpa', 'marks'])

Sets

In Python, the set allows you to create a random or an orderless collection of data. Lists and
dictionaries are ordered collections in Python where data has a sequence and an index for each data.
However, in Python, set is an unordered collection of data and it does not contain any duplicate
elements or values.

Code

Flowers={"Rose", "Lily","Lotus", "Sunflower", "Daisy","Rose"}


print(Flowers)
print(type(Flowers))
print(len(Flowers))

Output

{'Lily', 'Daisy', 'Lotus', 'Sunflower', 'Rose'}


<class 'set'>
5

You might also like