0% found this document useful (0 votes)
52 views42 pages

Module 1

Python is a popular, high-level programming language used for web development, software development, data science, and more. It has a simple syntax and can be used across operating systems. Popular applications built with Python include Instagram, Spotify, and Dropbox. Python supports object-oriented, procedural, and functional programming styles. Common data types in Python include integers, floats, strings, lists, dictionaries, and more.

Uploaded by

Parul Thalquotra
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)
52 views42 pages

Module 1

Python is a popular, high-level programming language used for web development, software development, data science, and more. It has a simple syntax and can be used across operating systems. Popular applications built with Python include Instagram, Spotify, and Dropbox. Python supports object-oriented, procedural, and functional programming styles. Common data types in Python include integers, floats, strings, lists, dictionaries, and more.

Uploaded by

Parul Thalquotra
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/ 42

Rupesh Kumar(2007563)

PYTHON PROGRAMMING LANGUAGE


Python is a high-level, general-purpose and a very popular programming language. Python
programming language (latest Python 3) is being used in web development, Machine Learning
applications, along with all cutting-edge technology in Software Industry. Python Programming
Language is very well suited for Beginners, also for experienced programmers with other
programming languages like C++ and Java.
Or

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

• web development (server-side),


• software development,
• mathematics,
• system scripting.

What can Python do?


• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon
as it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional
way.

Some of the most significant features of Python are:


• Easy to Code. ...
• Open Source and Free. ...
• Support for GUI. ...
• Object-Oriented Approach. ...
• High-Level Language. ...
• Integrated by Nature. ...
• Highly Portable. ...

Application of python
• Highly Dynamic. Web Development. Python can be used to make web-applications at a
rapid rate. ...
• Game Development. Python is also used in the development of interactive games. ...
• Machine Learning and Artificial Intelligence. ...
• Data Science and Data Visualization. ...
• Desktop GUI. ...
• Web Scraping Applications. ...
• Business Applications. ...
• CAD Applications.

App developed in python

Instagram

Pinterest

Spotify

Dropbox

Uber
Top Python Libraries List
Pandas
NumPy
Keras
TensorFlow
SciPy
PyTorch
LightGBM

Syntax in python
print("Hello, World!") Output: Hello world

Object python object


An Object is an instance of a Class. A class is like a blueprint while an instance is a copy
of the class with actual values. Python is object-oriented programming language that
stresses on objects i.e. it mainly emphasizes functions.
Syntax:
obj = MyClass()
print(obj.x)

Creating an Object
class Cars:
def __init__(self, m, p):
self.model = m
self.price = p
Audi = Cars("R8", 100000)
print(Audi.model)
print(Audi.price)
Output:
R8
100000

Data type
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
instance (object) of these classes.
Following are the standard or built-in data type of Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Tuple
• Dictionary

Standard data type in python


Object type Example literals/creation

Numbers 1234, 3.1415, 999L, 3+4j, Decimal

Strings 'spam', "guido's"

Lists [1, [2, 'three'], 4]

Dictionaries {'food': 'spam', 'taste': 'yum'}

Tuples (1,'spam', 4, 'U')

Files myfile = open('eggs', 'r')

Other types Sets, types, None, Booleans

Built-in Data Types


In programming, data type is an important concept.

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType


Getting the Data Type
You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x=5
print(type(x))

Internal Types
• Code.
• Frame.
• Traceback.
• Slice.
• Ellipsis.
• Xrange.

Code Objects:
Code objects are executable pieces of Python source that are byte-compiled.

Frame Objects
These are objects representing execution stack frames in Python. Frame objects contain all the
information the Python interpreter needs to know during a runtime execution environment.

Traceback Objects
When you make an error in Python, an exception is raised. If exceptions are not caught or "handled,"
the interpreter exits with some diagnostic information similar to the output shown below:

Traceback (innermost last): File "<stdin>", line N? in??? Error Name:


error reason

Slice Objects
Slice objects are created using the Python extended slice syntax. This extended syntax allows for
different types of indexing. Slice objects can also be generated by the slice () BIF.

Ellipsis Objects
Ellipsis objects are used in extended slice notations as demonstrated above. These objects are used
to represent the actual ellipses in the slice syntax (...). Like the Null object None, ellipsis objects also
have a single name, Ellipsis, and have a Boolean True value at all times.

XRange Objects
XRange objects are created by the BIF xrange(), a sibling of the range() BIF, and used when
memory is limited and when range() generates an unusually large data set. You can find out more
about range() and xrange().
Python Operators ?
An operator is a symbol that will perform mathematical operations on variables or
on values. Operators operate on operands (values) and return a result.
Python has 7 types of operators that you can use:

•Arithmetic Operators
•Relational Operators
• Assignment Operators
• Logical Operators
• Membership Operators
• Identity Operators
• Bitwise Operators
Let’s take an example:

2+3

Here, + is an operator for addition. It adds 2 and 3 and prints 5 in the interpreter. This
is an arithmetic operator.

What are operators in python?

Operators are special symbols in Python that carry out arithmetic or logical
computation. The value that the operator operates on is called the operand.

For example:

>>> 2+3
5

Here, + is the operator that performs addition. 2 and 3 are the operands and 5 is the
output of the operation.

Arithmetic operators
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.

Operator Meaning Example


+ Add two operands or unary plus x + y+ 2

- Subtract right operand from the left or unary minus x - y- 2

* Multiply two operands x*y

/ Divide left operand by the right one (always results into float) x/y

x % y (remainder of
% Modulus - remainder of the division of left operand by the right
x/y)

Floor division - division that results into whole number adjusted to the
// x // y
left in the number line

x**y (x to the power


** Exponent - left operand raised to the power of right
y)

Example 1: Arithmetic operators in Python


x = 15
y = 4

# Output: x + y = 19
print('x + y =',x+y)

# Output: x - y = 11
print('x - y =',x-y)

# Output: x * y = 60
print('x * y =',x*y)

# Output: x / y = 3.75
print('x / y =',x/y)

# Output: x // y = 3
print('x // y =',x//y)

# Output: x ** y = 50625
print('x ** y =',x**y)
Run Code

Output

x + y = 19
x - y = 11
x * y = 60
x / y = 3.75
x // y = 3
x ** y = 50625

Comparison operators

Comparison operators are used to compare values. It returns


either True or False according to the condition.
Operator Meaning Example

> Greater than - True if left operand is greater than the right x>y

< Less than - True if left operand is less than the right x<y

== Equal to - True if both operands are equal x == y

!= Not equal to - True if operands are not equal x != y

>= Greater than or equal to - True if left operand is greater than or equal to the right x >= y

<= Less than or equal to - True if left operand is less than or equal to the right x <= y

Example 2: Comparison operators in Python


x = 10
y = 12

# Output: x > y is False


print('x > y is',x>y)

# Output: x < y is True


print('x < y is',x<y)

# Output: x == y is False
print('x == y is',x==y)

# Output: x != y is True
print('x != y is',x!=y)

# Output: x >= y is False


print('x >= y is',x>=y)

# Output: x <= y is True


print('x <= y is',x<=y)
Run Code

Output

x > y is False
x < y is True
x == y is False
x != y is True
x >= y is False
x <= y is True

Logical operators
Logical operators are the and , or , not operators.
Operator Meaning Example

and True if both the operands are true x and y

or True if either of the operands is true x or y

not True if operand is false (complements the operand) not x

Example 3: Logical Operators in Python


x = True
y = False

print('x and y is',x and y)

print('x or y is',x or y)

print('not x is',not x)
Run Code

Output

x and y is False
x or y is True
not x is False

Here is the truth table for these operators.

Bitwise operators

Bitwise operators act on operands as if they were strings of binary digits. They operate
bit by bit, hence the name.

For example, 2 is 10 in binary and 7 is 111 .

In the table below: Let x = 10 ( 0000 1010 in binary) and y = 4 ( 0000 0100 in binary)
Operator Meaning Example

& Bitwise AND x & y = 0 ( 0000 0000 )

| Bitwise OR x | y = 14 ( 0000 1110 )

~ Bitwise NOT ~x = -11 ( 1111 0101 )

^ Bitwise XOR x ^ y = 14 ( 0000 1110 )

>> Bitwise right shift x >> 2 = 2 ( 0000 0010 )

<< Bitwise left shift x << 2 = 40 ( 0010 1000 )

Assignment operators
Assignment operators are used in Python to assign values to variables.

a = 5 is a simple assignment operator that assigns the value 5 on the right to the
variable a on the left.
There are various compound operators in Python like a += 5 that adds to the variable
and later assigns the same. It is equivalent to a = a + 5.

Operator Example Equivalent to

= x=5 x=5

+= x += 5 x=x+5

-= x -= 5 x=x-5

*= x *= 5 x=x*5

/= x /= 5 x=x/5

%= x %= 5 x=x%5

//= x //= 5 x = x // 5

**= x **= 5 x = x ** 5

&= x &= 5 x=x&5

|= x |= 5 x=x|5

^= x ^= 5 x=x^5

>>= x >>= 5 x = x >> 5

<<= x <<= 5 x = x << 5

Special operators

Python language offers some special types of operators like the identity operator or the
membership operator. They are described below with examples.
Identity operators
is and is not are the identity operators in Python. They are used to check if two values
(or variables) are located on the same part of the memory. Two variables that are equal
does not imply that they are identical.
Operator Meaning Example

is True if the operands are identical (refer to the same object) x is True

is not True if the operands are not identical (do not refer to the same object) x is not True

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

# Output: False
print(x1 is not y1)

# Output: True
print(x2 is y2)

# Output: False
print(x3 is y3)
Run Code

Output

False
True
False

Here, we see that x1 and y1 are integers of the same values, so they are equal as well
as identical. Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter
locates them separately in memory although they are equal.
Membership operators
in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.

Operator Meaning Example

in True if value/variable is found in the sequence 5 in x

not in True if value/variable is not found in the sequence 5 not in x

Example #5: Membership operators in Python


x = 'Hello world'
y = {1:'a',2:'b'}

# Output: True
print('H' in x)

# Output: True
print('hello' not in x)

# Output: True
print(1 in y)

# Output: False
print('a' in y)
Run Code

Output

True
True
True
False

Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly, 1 is key and 'a' is the value in dictionary y . Hence, 'a' in y returns False .

Standard Type Built-in Functions


Along with generic operators which we have just seen, Python also provides
some built-in functions that can be applied to all the basic object
types: cmp(), repr(), str(), type(), and the single reverse or back
quotes ( '' ) operator, which is functionally-equivalent to repr().
function operation

compares obj1 and obj2, returns integer i where:


i < 0 if obj1 < obj2
i > 0 if obj1 > obj2
cmp(obj1, obj2) i == 0 if obj1 == obj2

repr(obj)/' obj' returns evaluatable string representation of obj

str(obj) returns printable string representation of obj

type(obj) determines type of obj and return type object

Table 4.4. Standard Type Built-in Functions

cmp ()
The cmp() built-in function Compares two objects, say, obj1 ...

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object


input() Allowing user input

int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

Categorizing the Standard Types

If we were to be maximally verbose in describing the standard types, we would probably call them
something like Python's "basic built-in data object primitive types."

o "Basic," indicating that these are the standard or core types that Python provides
o "Built-in," due to the fact that these types come by default in Python
o "Data," because they are used for general data storage
o "Object," because objects are the default abstraction for data and functionality
o "Primitive," because these types provide the lowest-level granularity of data storage
o "Types," because that's what they are: data types!

Python Numbers
Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
• int
• float
• complex
Let’s see each one of them:
Int type
int (Integers) are the whole number, including negative numbers but not fractions. In Python,
there is no limit to how long an integer value can be.
Example 1: Creating int and checking type
• Python3
num = -8

# print the data type

print(type(num))

Output:
<class 'int'>

Float type
This is a real number with 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. . Some examples of numbers that are represented as floats
are 0.5 and -7.823457.
They can be created directly by entering a number with a decimal point, or by using
operations such as division on integers. Extra zeros present at the number’s end are
ignored automatically.
Example 1: Creating float and checking type
• Python3
num = 3/4

# print the data type

print(type(num))

Output:
<class 'float'>

Complex type
A complex number is a number that consists of the real and imaginary parts. For example,
2 + 3j is a complex number where 2 is the real component, and 3 multiplied by j is an
imaginary part.
Example 1: Creating Complex and checking type
• Python3
num = 6 + 9j
print(type(num))

Output:
<class 'complex'>

Python Built-in Functions


The built-in Python Functions which we are going to discuss in this article are as follows:

• print( ) function
• type( ) function
• input( ) function
• abs( ) function
• pow( ) function
• dir( ) function
• sorted( ) function
• max( ) function
• round( ) function
• divmod( ) function
• id( ) function
• ord( ) function
• len( ) function
• sum( ) function
• help( ) function

print( ) function
The print() function prints the specified message to the screen or another standard
output device.

The message that wants to print can be a string or any other object. This function
converts the object into a string before written to the screen.

Example 1: Print a string onto the screen:

print("Analytics Vidhya is the Largest Data Science Community over whole


world")

Output:

Analytics Vidhya is the Largest Data Science Community over whole world
Example 2: Print more than one object onto the screen:

print("Analytics Vidhya", "Chirag Goyal", "Data Scientist", "Machine Learning")

Output:

Analytics Vidhya Chirag Goyal Data Scientist Machine Learning

type( ) function
The type() function returns the type of the specified object.

Example 1: Return the type of the following object:

list_of_fruits = ('apple', 'banana', 'cherry', 'mango')


print(type(list_of_fruits))

Output:

<class 'tuple'>

Example 2: Return the type of the following objects:

variable_1 = "Analytics Vidhya"


variable_2 = 105
print(type(variable_1))
print(type(variable_2))

Output:

<class 'str'>
<class 'int'>

input( ) function
The input() function allows taking the input from the user.

Example: Use the prompt parameter to write the complete message after giving the
input:

a = input('Enter your name:')


print('Hello, ' + a + ' to Analytics Vidhya')

Output:

Enter your name:Chirag Goyal


Hello, Chirag Goyal to Analytics Vidhya

abs( ) function
The abs() function returns the absolute value of the specified number.

Example 1: Return the absolute value of a negative number:

negative_number = -676
print(abs(negative_number))

Output:

676

Example 2: Return the absolute value of a complex number:

complex_number = 3+5j
print(abs(complex_number))

Output:

5.830951894845301

The absolute value of a complex number is defined in the following way:

Image Source: Link


pow( ) function
The pow() function returns the calculated value of x to the power of y i.e, xy.

If a third parameter is present in this function, then it returns x to the power of y,


modulus z.

Example 1: Return the value of 3 to the power of 4:

x = pow(3, 4)
print(x)

Output:

81

Example 2: Return the value of 3 to the power of 4, modulus 5 (same as (3 * 3 * 3 * 3) %


5):

x = pow(3, 4, 5)
print(x)

Output:

dir( ) function
The dir() function returns all the properties and methods of the specified object, without
the values.

This function even returns built-in properties which are the default for all objects.

Example: Display the content of an object:

class Person:
name = "Chirag Goyal"
age = 19
country = "India"
education = "IIT Jodhpur"
print(dir(Person))

Output:

sorted( ) function
The sorted() function returns a sorted list of the specified iterable object.

You can specify the order to be either ascending or descending. In this function, Strings
are sorted alphabetically, and numbers are sorted numerically.

NOTE: If a list contains BOTH string values AND numeric values, then we cannot sort it.

Example 1: Sort the specified tuple in ascending order:

tuple = ("h", "b", "a", "c", "f", "d", "e", "g")


print(sorted(tuple))

Output:

['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Example 2: Sort the specified tuple in descending order:

tuple = ("h", "b", "a", "c", "f", "d", "e", "g")


print(sorted(tuple, reverse=True))

Output:
['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a']

max( ) function
The max() function returns the item with the maximum value or the item with the
maximum value in an iterable.

If the values this function takes are strings, then it is done using an alphabetical
comparison.

Example 1: Return the name with the highest value, ordered alphabetically:

names_tuple = ('Chirag', 'Kshitiz', 'Dinesh', 'Kartik')


print(max(names_tuple))

Output:

Kshitiz

Example 2: Return the item in a tuple with the highest value:

number_tuple = (2785, 545, -987, 1239, 453)


print(max(number_tuple))

Output:

2785

round( ) function
The round() function returns a floating-point number that is a rounded version of the
specified number, with the specified number of decimals.

The default number of decimals is 0, meaning that the function will return the nearest
integer.

Example 1: Round the specified positive number to the nearest integer:

nearest_number = round(87.76432)
print(nearest_number)
Output:

88

Example 2: Round the specified negative number to the nearest integer:

nearest_number = round(-87.76432)
print(nearest_number)

Output:

-88

Example 3: Round the specified number to the nearest integer:

nearest_number = round(87.46432)
print(nearest_number)

Output:

87

divmod( ) function
The divmod() function returns a tuple containing the quotient and the remainder when
the first argument i.e, the dividend is divided by the second argument i.e, the divisor.

Example 1: Display the quotient and the remainder when 7 is divided by 3:

x = divmod(7, 3)
print(x)

Output:

(2, 1)

Example 2: Display the quotient and the remainder when 72 is divided by 6:

x = divmod(72, 6)
print(x)
Output:

(12, 0)

id( ) function
The id() function returns a unique id for the specified object. Note that all the objects in
Python have their own unique id.

The id is assigned to the object when it is created.

The id is the object’s memory address and will be different for each time you run the
program. (except for some object that has a constant unique id, like integers from -5 to
256)

Example 1: Return the unique id of a tuple object:

names_tuple = ('Chirag', 'Kshitiz', 'Dinesh', 'Kartik')


print(id(names_tuple))

Output:

140727154106096

Example 2: Return the unique id of a string object:

string = "Analytics Vidhya is the Largest Data Science Community"


print(id(string))

Output:

140727154110000

ord( ) function
The ord() function returns the number representing the Unicode code of a specified
character.

Example 1: Return the integer that represents the character “h”:


x = ord("h")
print(x)

Output:

104

Example 2: Return the integer that represents the character “H”:

x = ord("H")
print(x)

Output:

72

len( ) function
The len() function returns the count of items present in a specified object.

When the object is a string, then the len() function returns the number of characters
present in that string.

Example 1: Return the number of items in a list:

fruit_list = ["apple", "banana", "cherry", "mango", "pear"]


print(len(fruit_list))

Output:

Example 2: Return the number of items in a string object:

string = "Analytics Vidhya is the Largest Data Science Community"


print(len(string))

Output:

54
sum( ) function
The sum() function returns a number, the sum of all items in an iterable.

If you are a beginner, I think that you don’t have a good understanding of what Iterables
and Iterators are. To learn these concepts, you can refer to the link.

Example 1: Start with the number 7, and add all the items in a tuple to this number:

a = (1, 2, 3, 4, 5)
print(sum(a, 7))

Output:

22

Example 2: Print the sum of all the elements of a list:

list = [1, 2, 3, 4, 5]
print(sum(list))

Output:

15

help( ) function
The help() function is used to display the documentation of modules, functions, classes,
keywords, etc.

If we don’t give an argument to the help function, then the interactive help utility starts
up on the console.

Example 1: Check the documentation of the print function in the python console.

help(print)

Output:
Related Modules Sequences

Python Strings

Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.

'hello' is the same as "hello".

You can display a string literal with the print() function:

Example
print("Hello")
print('Hello')
Try it Yourself »

Assign String to a Variable


Assigning a string to a variable is done with the variable name followed by an equal sign
and the string:

Example
a = "Hello"
print(a)

Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Or three single quotes:

Example
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

Note: in the result, the line breaks are inserted at the same position as in the code.

Strings are Arrays


Like many other popular programming languages, strings in Python 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.

Example
Get the character at position 1 (remember that the first character has the position 0):

a = "Hello, World!"
print(a[1])
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.

Example
Loop through the letters in the word "banana":

for x in "banana":
print(x)

Learn more about For Loops in our Python For Loops chapter.

String Length
To get the length of a string, use the len() function.

Example
The len() function returns the length of a string:

a = "Hello, World!"
print(len(a))

Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.

Example
Check if "free" is present in the following text:

txt = "The best things in life are free!"


print("free" in txt)

Use it in an if statement:

Example
Print only if "free" is present:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")

Learn more about If statements in our Python If...Else chapter.

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the
keyword not in.

Example
Check if "expensive" is NOT present in the following text:

txt = "The best things in life are free!"


print("expensive" not in txt)

Use it in an if statement:

Example
print only if "expensive" is NOT present:

txt = "The best things in life are free!"


if "expensive" not in txt:
print("No, 'expensive' is NOT present.")

List
A list represents a group of elements.
Lists are very similar to array but there is major difference, an array can store
only one type of elements whereas a list can store different type of elements.
Lists are mutable so we can modify it’s element.
A list can store different types of elements which can be modified.
Lists are dynamic which means size is not fixed.
Lists are represented using square bracket [ ].
Ex:- a = [10, 20, -50, 21.3, ‘Geekyshows’]
Ex:- a = [10, 20, 50]
Python Lists
❮ PreviousNext ❯

mylist = ["apple", "banana", "cherry"]

List
Lists are used to store multiple items in a single variable.

Lists are one of 4 built-in data types in Python used to store collections of data, the other
3 are Tuple, Set, and Dictionary, all with different qualities and usage.

Lists are created using square brackets:

Example
Create a List:

thislist = ["apple", "banana", "cherry"]


print(thislist)
Try it Yourself »

List Items
List items are ordered, changeable, and allow duplicate values.

List items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that lists are ordered, it means that the items have a defined order, and
that order will not change.

If you add new items to a list, the new items will be placed at the end of the list.
Note: There are some list methods that will change the order, but in general: the order
of the items will not change.

Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after
it has been created.

Allow Duplicates
Since lists are indexed, lists can have items with the same value:

Example
Lists allow duplicate values:

thislist = ["apple", "banana", "cherry", "apple", "cherry"]


print(thislist)

List Length
To determine how many items a list has, use the len() function:

Example
Print the number of items in the list:

thislist = ["apple", "banana", "cherry"]


print(len(thislist))

List Items - Data Types


List items can be of any data type:

Example
String, int and boolean data types:
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

A list can contain different data types:

Example
A list with strings, integers and boolean values:

list1 = ["abc", 34, True, 40, "male"]

type()
From Python's perspective, lists are defined as objects with the data type 'list':

<class 'list'>

Example
What is the data type of a list?

mylist = ["apple", "banana", "cherry"]


print(type(mylist))

Python Tuples
mytuple = ("apple", "banana", "cherry")

Tuple
Tuple – A tuple contains a group of elements which can be same or different
types.

Tuples are immutable.

It is similar to List but Tuples are read-only which means we can not modify it’s
element.

Tuples are used to store data which should not be modified.

It occupies less memory compare to list.


Tuples are represented using parentheses ( ).

Ex:- a = (10, 20, -50, 21.3, ‘Geekyshows’)

Example
Create a Tuple:

thistuple = ("apple", "banana", "cherry")


print(thistuple)
Try it Yourself »

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.

Tuple items are indexed, the first item has index [0], the second item has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items have a defined order, and
that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the
tuple has been created.

Allow Duplicates
Since tuples are indexed, they can have items with the same value:

Example
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
Try it Yourself »

Tuple Length
To determine how many items a tuple has, use the len() function:

Example
Print the number of items in the tuple:

thistuple = ("apple", "banana", "cherry")


print(len(thistuple))
Try it Yourself »

Create Tuple With One Item


To create a tuple with only one item, you have to add a comma after the item, otherwise
Python will not recognize it as a tuple.

Example
One item tuple, remember the comma:

thistuple = ("apple",)
print(type(thistuple))

#NOT a tuple
thistuple = ("apple")
print(type(thistuple))

Tuple Items - Data Types


Tuple items can be of any data type:

Example
String, int and boolean data types:
tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

A tuple can contain different data types:

Example
A tuple with strings, integers and boolean values:

tuple1 = ("abc", 34, True, 40, "male")

type()
From Python's perspective, tuples are defined as objects with the data type 'tuple':

<class 'tuple'>

Example
What is the data type of a tuple?

mytuple = ("apple", "banana", "cherry")


print(type(mytuple))

The tuple() Constructor


It is also possible to use the tuple() constructor to make a tuple.

Example
Using the tuple() method to make a tuple:

thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets


print(thistuple)

Python map() function


map() function returns a map object(which is an iterator) of the results after applying the
given function to each item of a given iterable (list, tuple etc.)
Syntax :
map(fun, iter)
Parameters :
fun : It is a function to which map passes each element of given iterable.
iter : It is a iterable which is to be mapped.
NOTE : You can pass one or more iterable to the map() function.
Returns :
Returns a list of the results after applying the given function
to each item of a given iterable (list, tuple etc.)

NOTE : The returned value from map() (map object) then can be passed to functions like list()
(to create a list), set() (to create a set) .

CODE 1
# Python program to demonstrate working

# of map.

# Return double of n

def addition(n):

return n + n

# We double all numbers using map()

numbers = (1, 2, 3, 4)

result = map(addition, numbers)

print(list(result))

Output :
[2, 4, 6, 8]

Set Type
A set is an unordered collection of elements much like a set in mathematics.
The order of elements is not maintained in the sets. It means the elements may
not appear in the same order as they are entered into the set.
A set does not accept duplicate elements.
Set is mutable so we can modify it.
Sets are unordered so we can not access its element using index.
Sets are represented using curly brackets { }
a = {10, 20, 30, “GeekyShows”, “Raj”, 40}

Creating a Set
A set is created by placing all the items (elements) inside curly braces {},
separated by comma. A set does not accept duplicate elements.
Elements can be of different types except mutable element, like list, set or
dictionary.
Ex:-
a = {10, 20, 30}
a = {10, 20, 30, “GeekyShows”, “Raj”, 40}
a = {10, 20, 30, “GeekyShows”, “Raj”, 40, 10, 20}

Accessing elements
Sets are unordered so we cannot access its element using index.
a = {10, 20, “GeekyShows”, “Raj”, 40}
a[0]
print(a)
Modifying Elements
Sets are mutable but as we can not access elements using index
so we can not modify it
Adding one Element
We can add a new element to set using add( ) method.
Syntax:-
set_name.add(new_element)
a.add(‘Python’)

Clearing All Elements


Clear ( ) Method is used remove all elements to the set
Syntax:- set_name.clear()
Ex:- a.clear()
Some other Methods of set
• intersection ( )
• union ( )
• difference ( )
• issubset ( )
• issuperset ( )

Method union(other_set)
The union() function returns a new set by collecting all of the elements from current set and the
other_set.

Method intersection(other_set)
The intersection() function returns a new set by collecting common elements from the current set
and the other_set.

Method difference(other_set)
The difference() method will return a set, where the final set contains all of the elements of the
first set except the common elements of those two sets.

Method add(elem)
Add the element elem in the set.

Method discard(elem)
Remove the element elem from the set. This will work when the elem is present in the set. There
is another method called remove(). In the remove(), it will raise KeyError if the item is not present
in the set.

Example Code
mySet1 = {1, 2, 5, 6}
mySet2 = {8, 5, 3, 4}
mySet3 = set(range(15)) # all elements from 0 to 14 in the set
mySet4 = {10, 20, 30, 40}
print(set(mySet1.union(mySet2)))
print(set(mySet1.intersection(mySet2)))
print(set(mySet1.difference(mySet2)))

print(mySet3.issuperset(mySet1))
print(mySet1.isdisjoint(mySet4))

mySet4.add(45)
print(mySet4)

mySet4.discard(40)
print(mySet4)

Output
set([1, 2, 3, 4, 5, 6, 8])
set([5])
set([1, 2, 6])
True
True
set([40, 10, 20, 45, 30])
set([10, 20, 45, 30])

You might also like