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

Python Unit-1

The document provides an overview of Python programming, including its history, features, and evolution from Python 1.x to 3.x. It highlights key milestones, the role of the Python Software Foundation, and the language's characteristics such as readability, dynamic typing, and extensive libraries. Additionally, it covers various types of literals in Python, including string, numeric, and boolean literals, with examples demonstrating their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Python Unit-1

The document provides an overview of Python programming, including its history, features, and evolution from Python 1.x to 3.x. It highlights key milestones, the role of the Python Software Foundation, and the language's characteristics such as readability, dynamic typing, and extensive libraries. Additionally, it covers various types of literals in Python, including string, numeric, and boolean literals, with examples demonstrating their usage.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Department of Computer Science

I – B.Sc., Computer Science


23UCSCC13
23UCSCC13: PYTHON PROGRAMMING
Unit-1:

Basics of Python Programming: History of Python-Features


Features of Python-Literal-
Python
Constants-Variables - Identifiers
Identifiers–Keywords-Built-in
in Data Types
Types-Output
Statements – Input Statements
Statements-Comments – Indentation- Operators-Expressions-
Operators
Type conversions. Python Arrays: Defining and Processing Arrays – Array
methods.

History of Python

Background and Development

 Origin:: Python was developed in the late 1980s by Guido van Rossum,
Rossum a Dutch
programmer, while he was working at the Centrum Wiskunde & Info Informatica (CWI) in
the Netherlands.
 Inspiration:: Guido van Rossum aimed to create a language with an emphasis on code
readability and simplicity, which was lacking in the languages at the time. He was
inspired by the ABC language
language, a teaching language he had previously worked on.
 Purpose:: Python was designed as a successor to the ABC language, with improvements
in handling exceptions and interfacing with the Amoeba operating system.
 Initial Release:: The first official version, Python 0.9.0,, was released in 1991.

2. Why the Name 'Python'?

 Guido chose the name "Python" not after the snake but as a reference to the popular
British comedy show “Monty Python's Flying Circus.”
 This influence led to Python's lighthearted naming conventions and its focus on
readability and enjoyment in programming.

3. Early Development (Python 1.x)

 Python 1.0: Released in January 1994


1994,, Python 1.0 introduced essential features like
functions, exception handling, and the module system.
 Notable Features:
o Lambda, map, filter, and reduce functions were added, drawing from
functional programming languages.
o The import system allowed code organization and reuse.
 Subsequent Versions: Versions from 1.1 to 1.6 included incremental improvements,
expanding functionality and the standard library.

4. Python 2.x Era

 Python 2.0: Released in October 2000, Python 2.0 brought significant advancements:
o List Comprehensions: Simplified syntax for creating lists.
o Garbage Collection: Added automatic memory management.
o Unicode Support: Expanded Python's ability to handle international character
sets.
 Development Community: Python 2.0 was the first release developed collaboratively
by the open-source community, marking a shift in its development process.
 Subsequent Updates: Many 2.x versions were released over the years, refining and
adding features, and Python 2.7 (2010) became the final release in the Python 2 series.
 End of Support: Python 2.x support officially ended on January 1, 2020, urging users
to migrate to Python 3.

5. Python 3.x – The Modern Python

 Python 3.0: Released in December 2008, Python 3 was a major revision aimed at
fixing fundamental design flaws:
o Enhanced Syntax and Readability: Emphasis on readability and reduced
ambiguity.
o Print Function: Replaced print as a statement with print() as a function.
o New Integer Division: Division of integers produces a float (5 / 2 = 2.5), while
// performs integer division.
o Unicode by Default: All strings are Unicode by default, making Python more
versatile with international languages.
o Standard Library Overhaul: Many modules were improved or rewritten for
better consistency and performance.
 Backward Incompatibility: Python 3 was intentionally made incompatible with
Python 2 to eliminate legacy issues, though this posed a challenge for developers to
migrate their codebases.
 Python 3.x Versions: Subsequent 3.x releases introduced features like async
programming, f-strings, type hinting, and data classes.

6. The Python Software Foundation (PSF)

 Formation: Established in 2001, the Python Software Foundation (PSF) is a non-profit


organization responsible for managing and advancing the Python language.
 Role: PSF oversees the development of Python, manages trademarks, and provides
grants for Python-related projects and conferences.
 Community-Driven Development: Python is developed in a collaborative, open-
source model. The Python Enhancement Proposal (PEP) process allows the community
to suggest changes.

7. Key Milestones in Python's Evolution

 Python 1.0 (1994): Introduced core features such as functions, modules, and
exceptions.
 Python 2.0 (2000): Introduced garbage collection, list comprehensions, and the first
community-driven development approach.
 Python 2.7 (2010): Last version of Python 2, widely used until end of support in 2020.
 Python 3.0 (2008): Major rewrite with improved consistency, Unicode support, and
clean syntax.
 Python 3.5 (2015): Added async and await for asynchronous programming.
 Python 3.6 (2016): Introduced f-strings for efficient string formatting.
 Python 3.9 (2020): End of life for Python 2.x and enhanced modern features.

8. Python Today and Future Direction

 Popularity: Python is one of the most popular programming languages in the world,
thanks to its readability, community support, and versatility in web development, data
science, AI, automation, and more.
 Python 3.x Continuity: Python's current and future versions continue in the 3.x series,
focusing on language stability, performance improvements, and adding capabilities that
meet modern needs (e.g., data science, machine learning).
 PEP 563 and Beyond: The future of Python is community-driven, with the PEP process
continuing to shape its evolution. Recent PEPs focus on performance enhancements,
syntax improvements, and expanding support for typing and async programming.

Features of Python

Python is known for its simplicity and powerful capabilities

1. Simple and Easy to Learn

 Readability: Python's syntax is straightforward and similar to English, which makes


the code more readable.
 Minimal Setup: Python requires minimal setup and is easy to install and start with.
 Beginner-Friendly: Ideal for beginners, Python's simplicity allows newcomers to grasp
concepts without getting bogged down by complex syntax.
2. Interpreted Language

 Line-by-Line Execution: Python code is executed one line at a time, making it easier to
debug errors as they appear.
 No Compilation: Unlike compiled languages (e.g., C, Java), Python does not require
compilation before running. This reduces development time.
 REPL: Python provides an interactive shell (REPL - Read-Eval-Print Loop) where users
can execute Python statements line by line.

3. Dynamically Typed Language

 No Type Declarations: Variables do not require explicit type declarations; types are
assigned at runtime based on the variable’s value.
 Flexibility: This feature allows programmers to write code faster without worrying
about declaring data types.
 Reduced Code Complexity: Dynamic typing reduces verbosity and complexity, making
the code concise.

4. Object-Oriented Language

 Classes and Objects: Python supports object-oriented programming (OOP), enabling


users to define classes and create objects, which makes it suitable for large-scale
projects.
 Encapsulation, Inheritance, and Polymorphism: Python supports OOP principles like
encapsulation, inheritance, and polymorphism, making it possible to design reusable
and organized code.
 Support for Multiple Paradigms: Python combines OOP with procedural and
functional programming, making it versatile.

5. Extensive Standard Library

 Built-In Modules: Python's standard library includes modules for various purposes
like file I/O, system calls, sockets, and more.
 Libraries for All Needs: Python’s standard library supports web development, data
manipulation, math operations, regular expressions, and more.
 Reduced Need for External Packages: This library reduces the need for installing
external packages, as it covers many common programming requirements.

6. Platform Independent

 Cross-Platform Compatibility: Python code can run on multiple operating systems,


including Windows, macOS, and Linux, without modification.
 "Write Once, Run Anywhere": Python’s platform independence allows code to be
portable across different platforms, making it popular for cross-platform development.
 Interpreter Availability: Python interpreters are available on almost all modern
platforms, making Python highly accessible.

7. Open Source

 Free to Use: Python is open-source, meaning it’s freely available for anyone to
download, use, and modify.
 Community Contributions: Python’s development is driven by a global community of
contributors who suggest enhancements, contribute code, and participate in
discussions.
 Python Software Foundation (PSF): The PSF manages Python's development, and the
open-source model ensures continual improvement.

8. Support for Functional Programming

 Lambda Functions: Python supports lambda (anonymous) functions, allowing simple,


one-line functions for quick calculations.
 Higher-Order Functions: Functions like map(), filter(), and reduce() facilitate
functional programming.
 Immutability with Tuples: Python supports immutable data structures, such as tuples,
which align with functional programming paradigms.

9. High-Level Language

 Abstraction from Machine Language: As a high-level language, Python abstracts away


details of machine code, memory management, and hardware.
 Focus on Problem-Solving: Python allows programmers to focus on solving problems
rather than managing memory or system architecture.
 Readability and Ease of Use: Python's high-level nature makes it easier to write, read,
and maintain code.

10. Portability

 Uniform Behavior Across Platforms: Python code behaves consistently across


different platforms due to the interpreter’s uniformity.
 Wide Range of Applications: Python is used in various fields like web development,
data science, machine learning, and automation, all requiring portability.
 Broad Compatibility: Libraries and modules, such as NumPy, Pandas, and TensorFlow,
also support cross-platform compatibility.

11. Large Community Support

 Global Community: Python boasts a large and active global community, offering
support through forums, tutorials, and resources.
 Comprehensive Documentation: Python.org provides extensive documentation for all
Python versions, helping users to understand Python and its libraries.
 Third-Party Libraries and Packages: Python’s community maintains a vast repository
of third-party libraries and packages, covering a broad range of functionalities.

12. Support for GUI Programming

 Tkinter: Python includes Tkinter, a library for building simple graphical user
interfaces.
 Other GUI Frameworks: External libraries like PyQt, Kivy, and wxPython allow for
more advanced GUI development.
 Cross-Platform GUIs: These libraries are cross-platform, enabling GUI applications to
run on different operating systems.

13. Embeddable and Extensible

 Embedding: Python can be embedded in other languages to provide scripting


capabilities (e.g., embedding Python in C/C++ programs).
 Extensibility: Python’s functionality can be extended by adding modules written in
other languages like C, C++, and Java.
 Customization and Flexibility: This feature allows Python to be tailored to meet the
specific needs of applications.

14. Integrated with Database Systems

 Database Support: Python offers support for databases like MySQL, PostgreSQL,
SQLite, MongoDB, and others.
 Libraries and Modules: Libraries such as sqlite3, SQLAlchemy, and PyMySQL enable
database connectivity.
 Data-Driven Applications: These integrations make Python suitable for data-driven
applications and back-end development.

15. Automatic Memory Management (Garbage Collection)

 Automatic Garbage Collection: Python handles memory allocation and deallocation


automatically, freeing unused memory.
 Ease of Use: This reduces the need for manual memory management, minimizing the
risk of memory leaks.
 Reference Counting and Garbage Collector: Python uses a combination of reference
counting and a cyclic garbage collector.

16. Extensive Libraries and Support for Specialized Domains

 Scientific and Numeric Computing: Libraries like NumPy, SciPy, and Pandas enable
advanced mathematical and statistical computations.
 Data Science and Machine Learning: Libraries like TensorFlow, Keras, and scikit-
learn support machine learning and data science.
 Web Development: Frameworks like Django and Flask simplify web development.
 Automation and Scripting
Scripting: Modules like os, sys, and subprocess make Python ideal for
scripting and automation tasks.

17. Ease of Deployment


yment and Integration

 Simplicity of Deployment
Deployment:: Python applications can be packaged easily, which
simplifies deployment.
 API Integration:: Python’s simplicity allows easy integration with various APIs,
especially for web development and data science.
 Interoperability with Other Languages
Languages:: Python is compatible with languages like
Java, C, and C++, facilitating the integration of Python with other systems.

literal

A literal in Python is a syntax that is used to completely express a fixed value of a specific
data type. Literals are constants that are self-explanatory and don’t need to be computed or
evaluated. They are used to provide variable values or to directly utilize them in expressions.
Generally, literals are a notation for representing a fixed value in source
urce code. They can also
be defined as raw values or data given in variables or constants. In this article, we will
explore the different types of literals in Python, along with examples
mples to demonstrate their
usage.

Literals in Python

Table of Content
 Python String Literals
 Python Character Literal
 Python Numeric Literal
 Python Boolean Literal
 Python Literal Collections
 Python Special Literal
Types of Literals in Python
Python supports various types of literals, such as numeric literals, string literals, Boolean
literals, and more. Let’s explore different types of literals in Python with examples:
Python String Literals
A string is literal and can be created by writing a text(a group of Characters ) surrounded by
a single(”), double(“), or triple quotes. We can write multi-line strings or display them in the
desired way by using triple quotes. Here geekforgeeks is a string literal that is assigned to a
variable(s). Here is an example of a Python string literal.
Python

# in single quote
s = 'geekforgeeks'

# in double quotes
t = "geekforgeeks"

# multi-line String
m = '''geek
for
geeks'''

print(s)
print(t)
print(m)

Output

geekforgeeks
geekforgeeks
geek
for
geeks
Python Character Literal
It is also a type of Python string literal where a single character is surrounded by single or
double quotes.
Python

# character literal in single quote


v = 'n'

# character literal in double quotes


w = "a"

print(v)
print(w)

Output

n
a
Python Numeric Literal
They are immutable and there are three types of numeric literal:
 Integer
 Float
 Complex
Integer
Both positive and negative numbers including 0. There should not be any fractional part. In
this example, We assigned integer literals (0b10100, 50, 0o320, 0x12b) into different
variables. Here, ‘a‘ is a binary literal, ‘b’ is a decimal literal, ‘c‘ is an octal literal, and ‘d‘ is a
hexadecimal literal. But on using the print function to display a value or to get the output
they were converted into decimal.
Python

# integer literal

# Binary Literals
a = 0b10100

# Decimal Literal
b = 50

# Octal Literal
c = 0o320

# Hexadecimal Literal
d = 0x12b

print(a, b, c, d)

Output

20 50 208 299
Float
These are real numbers having both integer and fractional parts. In this example, 24.8 and
45.0 are floating-point literals because both 24.8 and 45.0 are floating-point numbers.
Python

# Float Literal
e = 24.8
f = 45.0

print(e, f)

Output

24.8 45.0
Complex
The numerals will be in the form of a + bj, where ‘a’ is the real part and ‘b‘ is the complex
part. Numeric literal [ Complex ]
Python

z = 7 + 5j

# real part is 0 here.


k = 7j
print(z, k)

Output

(7+5j) 7j
Python Boolean Literal
There are only two Boolean literals in Python. They are true and false. In
Python, True represents the value as 1, and False represents the value as 0. In this example
‘a‘ is True and ‘b‘ is False because 1 is equal to True.
Python

a = (1 == True)
b = (1 == False)
c = True + 3
d = False + 7

print("a is", a)
print("b is", b)
print("c:", c)
print("d:", d)

Output

a is True
b is False
c: 4
d: 7
Python Literal Collections
Python provides four different types of literal collections:
1. List literals
2. Tuple literals
3. Dict literals
4. Set literals
List literal
The list contains items of different data types. The values stored in the List are separated by
a comma (,) and enclosed within square brackets([]). We can store different types of data in
a List. Lists are mutable.
Python

number = [1, 2, 3, 4, 5]
name = ['Amit', 'kabir', 'bhaskar', 2]
print(number)
print(name)

Output

[1, 2, 3, 4, 5]
['Amit', 'kabir', 'bhaskar', 2]
Tuple literal
A tuple is a collection of different data-type. It is enclosed by the parentheses ‘()‘ and each
element is separated by the comma(,). It is immutable.
Python

even_number = (2, 4, 6, 8)
odd_number = (1, 3, 5, 7)

print(even_number)
print(odd_number)

Output

(2, 4, 6, 8)
(1, 3, 5, 7)
Dictionary literal
The dictionary stores the data in the key-value pair. It is enclosed by curly braces ‘{}‘ and
each pair is separated by the commas(,). We can store different types of data in a dictionary.
Dictionaries are mutable.
Python

alphabets = {'a': 'apple', 'b': 'ball', 'c': 'cat'}


information = {'name': 'amit', 'age': 20, 'ID': 20}

print(alphabets)
print(information)

Output

{'a': 'apple', 'b': 'ball', 'c': 'cat'}


{'name': 'amit', 'age': 20, 'ID': 20}
Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each element is
separated by the comma(,).
Python

vowels = {'a', 'e', 'i', 'o', 'u'}


fruits = {"apple", "banana", "cherry"}

print(vowels)
print(fruits)

Output

{'e', 'u', 'i', 'o', 'a'}


{'banana', 'cherry', 'apple'}
Constants

 Python Constant is a variable whose value cannot be changed throughout the program.
Certain values are fixed and are universally proven to be true. These values cannot be changed
over time. Such types of values are called as Constants. We can think of Python Constants as a
bag full of fruits, but these fruits cannot be removed or changed with other fruits.

Note – Unlike other programming languages, Python does not contain any constants. Instead,
Python provides us a Capitalized naming convention method. Any variable written in the Upper
case is considered as a Constant in Python.

Rules to be followed while declaring a Constant

1. Python Constants and variable names should contain a combination of lowercase (a-z) or
capital (A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when
declaring a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example,
makes more sense than V. It simplifies the coding process.
Assigning Values to Constants

Constants are typically declared and assigned in a module in Python. In this case, the module is a
new file containing variables, functions, and so on that is imported into the main file. Constants
are written in all capital letters with underscores separating the words within the module.

We create a separate file for declaring constants. We then use this file to import the constant
module in the main.py file from the other file.

Example
Copy Code

# create a separate constant.py file


PI = 3.14
GRAVITY = 9.8

Copy Code

# main.py file
import constant as const

print('Value of PI:', cons.PI)


print('Value of Gravitational force:', cons.GRAVITY)
Output
Value of PI: 3.14
Value of Gravitational force: 9.8
Variables
Python variables are the reserved memory locations used to store values with in a Python
Program. This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, Python interpreter allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to Python
variables, you can store integers, decimals or characters in these variables.
Creating Python Variables
Python variables do not need explicit declaration to reserve memory space or you can say to
create a variable. A Python variable is created automatically when you assign a value to it. The
equal sign (=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the
right of the = operator is the value stored in the variable. For example −
counter =100# Creates an integer variable
miles =1000.0# Creates a floating point variable
name ="Zara Ali"# Creates a string variable
Printing Python Variables
Once we create a Python variable and assign a value to it, we can print it
using print() function. Following is the extension of previous example and shows how to print
different variables in Python:
counter =100# Creates an integer variable
miles =1000.0# Creates a floating point variable
name ="Zara Ali"# Creates a string variable

print(counter)
print(miles)
print(name)
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables,
respectively. When running the above Python program, this produces the following result −
100
1000.0
Zara Ali
Variable Types in Python

1. Local Variable in Python

2. Global Variable in Python


Python Local Variable
Python Local Variables are defined inside a function. We can not access variable outside the
function.
example to show the usage of local variables:
defsum(x,y):
sum= x + y
returnsum
print(sum(5,10))
Output:
15

Python Global Variable


Any variable created outside a function can be accessed within any function and so they have
global scope. Following is an example of global variables:
x =5
y =10
defsum():
sum= x + y
returnsum
print(sum())
This will produce the following result:
15

Identifiers

Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore. The identifier should start with a character or
Underscore then use a digit. The characters are A-Z or a-z, an Underscore(_), and digit (0-9).
We should not use special character (! #, @, $, %,) in identifiers.

Rules for Naming an Identifier

 Identifiers cannot be a keyword.

 Identifiers are case-sensitive.


 It can have a sequence of letters and digits. However, it must begin with a letter or _.
The first letter of an identifier cannot be a digit.
 It's a convention to start an identifier with a letter rather _.
 Whitespaces are not allowed.

 We cannot use special symbols like !, @, #, $, and so on.

Keywords

Keywords are predefined, reserved words used in Python programming that have special
meanings to the compiler.

We cannot use a keyword as a variable name, function name, or any other identifier. They are
used to define the syntax and structure of the Python language.
All the keywords except True, False and None are in lowercase and they must be
Python Keywords
Here is the list of some reserved keywords in Python that cannot be used as identifiers.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not await
class form or async
continue global pass

Keyword Description

and A logical operator


as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.


is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

Built-in Data Types

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 Pytho
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value
can be integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
 Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer
value can be.
 Float – This value is represented by float class. It 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.
 Complex Numbers – Complex number is represented by complex class. It is specified
as (real part) + (imaginary part)j. For example – 2+3j
# Python program to
# demonstrate numeric value

a =5
print("Type of a: ", type(a))

b =5.0
print("\nType of b: ", type(b))

c =2+4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>

Type of b: <class 'float'>

Type of c: <class 'complex'>


Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences
allows to store multiple values in an organized and efficient fashion. There are several
sequence types in Python –
 String
 List
 Tuple
String
In Python, Strings 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.

Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.

# Python Program for


# Creation of String

# Creating a String
# with single Quotes
String1 ='Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String
# with double Quotes
String1 ="I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))

# Creating a String
# with triple Quotes
String1 ='''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

# Creating String with triple


# Quotes allows multiple lines
String1 ='''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
<class 'str'>
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life

Accessing elements of String


In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String,
e.g. -1 refers to the last character, -2 refers to the second last character and so on.

Python3

# Python Program to Access


# characters of String

String1 ="GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


s
.
List
Lists are just like the arrays, declared in other languages which is a ordered collection of
data. It is very flexible as the items in a list do not need to be of the same type.

Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3

# Python program to demonstrate


# Creation of List

# Creating a List
List=[]
print("Initial blank List: ")
print(List)

# Creating a List with


# the use of a String
List=['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List=["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List=[['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]

List with the use of String:


['GeeksForGeeks']

List containing multiple values:


Geeks
Geeks

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
Accessing elements of List
In order to access the list items refer to the index number. Use the index operator [ ] to
access an item in a list. In Python, negative sequence indexes represent positions from the
end of the array. Instead of having to compute the offset as in List[len(List)-3], it is enough to
just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last
item, -2 refers to the second-last item, etc.
# Python program to demonstrate
# accessing of element from list

# Creating a List with


# the use of multiple values
List=["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference
between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is
created. It is represented by tuple class.

Creating Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping of the data sequence. Tuples can contain any
number of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one
element in the parentheses is not sufficient, there must be a trailing ‘comma’ to make it a
tuple.
# Python program to demonstrate
# creation of Set

# Creating an empty tuple


Tuple1 =()
print("Initial empty Tuple: ")
print(Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 =('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 =[1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 =tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# Creating a Tuple
# with nested tuples
Tuple1 =(0, 1, 2, 3)
Tuple2 =('python', 'geek')
Tuple3 =(Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))

Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
Accessing elements of Tuple
In order to access the tuple items refer to the index number. Use the index operator [ ] to
access an item in a tuple. The index must be an integer. Nested tuples are accessed using
nested indexing.
Python3

# Python program to
# demonstrate accessing tuple

tuple1 =tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])
Output:
First element of tuple
1

Last element of tuple


5

Third last element of tuple


3
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal to
True are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can
be evaluated in Boolean context as well and determined to be true or false. It is denoted by
the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw
an error.

# Python program to
# demonstrate boolean type

print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
File "/home/7e8862763fb66153d70824099d4f5fb7.py", line 8, in
print(type(true))
NameError: name 'true' is not defined
Set
In Python, Set is an unordered collection of data type 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.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence
by placing the sequence inside curly braces, separated by ‘comma’. Type of elements in a set
need not be the same, various mixed-up data type values can also be passed to the set.

# Python program to demonstrate


# Creation of Set in Python

# Creating a Set
set1 =set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 =set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 =set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 =set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}

Accessing elements of Sets


Set items cannot be accessed by referring to an index, since sets are unordered the items has
no index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.

# Python program to demonstrate


# Accessing of elements in a set

# Creating a set
set1 =set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
fori inset1:
print(i, end =" ")

# Checking the element


# using in keyword
print("Geeks"inset1)
Output:
Initial set:
{'Geeks', 'For'}

Elements of set:
Geeks For

True

Note – To know more about sets, refer Python Sets.


Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like
a map, which unlike other Data Types that hold only single value as an element, Dictionary
holds 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’.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’. Values in a dictionary can be of any datatype and can
be duplicated, whereas keys can’t be repeated and must be immutable. Dictionary can also
be created by the built-in function dict(). An empty dictionary can be created by just placing
it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be
treated distinctly.

# Creating an empty Dictionary


Dict={}
print("Empty Dictionary: ")
print(Dict)

# Creating a Dictionary
# with Integer Keys
Dict={1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

# Creating a Dictionary
# with Mixed keys
Dict={'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)

# Creating a Dictionary
# with dict() method
Dict=dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)

# Creating a Dictionary
# with each item as a Pair
Dict=dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}

Accessing elements of Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside
square brackets. There is also a method called get() that will also help in accessing the
element from a dictionary.
Python3

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict={1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")
print(Dict.get(3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Number
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
num =-8

# print the data type


print(type(num))
Output:
<class 'int'>
Example 2: Performing arithmetic Operations on int type
a =5
b =6

# Addition
c =a +b
print("Addition:",c)

d =9
e =6

# Subtraction
f =d -e
print("Subtraction:",f)

g =8
h =2

# Division
i =g //h
print("Division:",i)

j =3
k =5

# Multiplication
l =j *k
print("Multiplication:",l)

m =25
n =5

# Modulus
o =m %n

print("Modulus:",o)

p =6
q =2

# Exponent
r =p **q
print("Exponent:",r)
Output:
Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36
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
num =3/4

# print the data type


print(type(num))
Output:
<class 'float'>
As we have seen, dividing any two integers produces a float.
A float is also produced by running an operation on two floats, or a float and an integer.

num =6*7.0

print(type(num))
Output:
<class 'float'>
Example 2: Performing arithmetic Operations on float type
 Python3
a =5.5
b =3.2

# Addition
c =a +b
print("Addition:", c)

# Subtraction
c =a-b
print("Subtraction:", c)

# Division
c =a/b
print("Division:", c)

# Multiplication
c =a*b
print("Multiplication:", c)
Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place
can be inaccurate.
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'>
Example 2: Performing arithmetic operations on complex type
a =1+5j
b =2+3j

# Addition
c =a +b
print("Addition:",c)

d =1+5j
e =2-3j

# Subtraction
f =d -e
print("Subtraction:",f)

g =1+5j
h =2+3j

# Division
i =g /h
print("Division:",i)

j =1+5j
k =2+3j

# Multiplication
l =j *k
print("Multiplication:",l)
Output:
Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)
Type Conversion between numbers
We can convert one number into the other form by two methods:
 Using Arithmetic Operations: We can use operations like addition, subtraction to
change the type of number implicitly(automatically), if one of the operands is float. This
method is not working for complex numbers.
Example: Type conversion using arithmetic operations
a =1.6
b =5

c =a +b

print(c)
Output:
6.6
 Using built-in functions: We can also use built-in functions like int(), float() and
complex() to convert into different types explicitly.
Example: Type conversion using built-in functions
 Python3
a =2
print(float(a))

b =5.6
print(int(b))

c ='3'
print(type(int(c)))

d ='5.6'
print(type(float(c)))

e =5
print(complex(e))

f =6.5
print(complex(f))
Output:
2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
When we convert float to int, the decimal part is truncated.
Note:
1. We can’t convert a complex data type number into int data type and float data type
numbers.
2. We can’t apply complex built-in functions on strings.
Decimal Numbers in Python
Arithmetic operations on the floating number can give some unexpected results. Let’s
consider a case where we want to add 1.1 to 2.2. You all must be wondering that the result of
this operation should be 3.3 but let’s see the output given by Python.
Example:
a =1.1
b =2.2
c =a+b

print(c)
Output:
3.3000000000000003
You can the result is unexpected. Let’s consider another case where we will subtract 1.2 and
1.0. Again we will expect the result as 0.2, but let’s see the output given by Python.
Example:
 Python3
a =1.2
b =1.0
c =a-b

print(c)
Output:
0.19999999999999996
Example:
 Python3
importdecimal

a =decimal.Decimal('1.1')
b =decimal.Decimal('2.2')

c =a+b
print(c)
Output
3.3
Random Numbers in Python
Python provides a random module to generate pseudo-random numbers. This module can
create random numbers, select a random element from a sequence in Python, etc.
Example 1: Creating random value
 Python3
importrandom

print(random.random())
Output
0.9867200671824407
Example 2: Selecting random element from string or list
 Python3
importrandom

s ='geeksforgeeks'
L =[1, 2,3, 5, 6, 7, 7, 8, 0]
print(random.choice(s))
print(random.choice(L))
Output
f
0
Note: For more information about random numbers, refer to our Random Number tutorial
Python Mathematics
The math module of Python helps to carry different mathematical operations trigonometry,
statistics, probability, logarithms, etc.
Example:
 Python3
# importing "math" for mathematical operations
importmath

a =3.5

# returning the ceil of 3.5


print("The ceil of 3.5 is : ", end="")
print(math.ceil(a))

# returning the floor of 3.5


print("The floor of 3.5 is : ", end="")
print(math.floor(a))

# find the power


print("The value of 3.5**2 is : ",end="")
print(pow(a,2))
# returning the log2 of 16
print("The value of log2 of 3.5 is : ", end="")
print(math.log2(a))

# print the square root of 3.5


print("The value of sqrt of 3.5 is : ", end="")
print(math.sqrt(a))

# returning the value of sine of 3.5


print("The value of sine of 3.5 is : ", end="")
print(math.sin(a))
Output
The ceil of 3.5 is : 4
The floor of 3.5 is : 3
The value of 3.5**2 is : 12.25
The value of log2 of 3.5 is : 1.8073549220576042
The value of sqrt of 3.5 is : 1.8708286933869707
The value of sine of 3.5 is : -0.35078322768961984

Boolean
Python boolean type is one of the built-in data types provided by Python, which represents
one of the two values i.e. True or False. Generally, it is used to represent the truth values of
the expressions. For example, 1==1 is True whereas 2<1 is False.
Python Boolean Type
The boolean value can be of two types only i.e. either True or False. The output <class
‘bool’> indicates the variable is a boolean data type.

Example: Boolean type

 Python3
a =True
type(a)

b =False
type(b)
Output:
<class 'bool'>
<class 'bool'>
Evaluate Variables and Expressions
We can evaluate values and variables using the Python bool() function. This method is used
to return or convert a value to a Boolean value i.e., True or False, using the standard truth
testing procedure.
Syntax:
bool([x])

Example: Python bool() method


 Python3
# Python program to illustrate
# built-in method bool()

# Returns False as x is not equal to y


x =5
y =10
print(bool(x==y))

# Returns False as x is None


x =None
print(bool(x))

# Returns False as x is an empty sequence


x =()
print(bool(x))

# Returns False as x is an empty mapping


x ={}
print(bool(x))

# Returns False as x is 0
x =0.0
print(bool(x))

# Returns True as x is a non empty string


x ='GeeksforGeeks'
print(bool(x))
Output
False
False
False
False
False
True
We can also evaluate expression without using the bool() function also. The Booleans values
will be returned as a result of some sort of comparison. In the example below the variable
res will store the boolean value of False after the equality comparison takes place.

Example: Boolean value from the expression

 Python3
# Declaring variables
a =10
b =20
# Comparing variables
print(a ==b)
Output:
False
Integers and Floats as Booleans
Numbers can be used as bool values by using Python’s built-in bool() method. Any integer,
floating-point number, or complex number having zero as a value is considered as False,
while if they are having value as any positive or negative number then it is considered as
True.
 Python3
var1 =0
print(bool(var1))

var2 =1
print(bool(var2))

var3 =-9.7
print(bool(var3))
Output:
False
True
True
Boolean Operators
Boolean Operations are simple arithmetic of True and False values. These values can be
manipulated by the use of boolean operators which include AND, Or, and NOT. Common
boolean operations are –
 or
 and
 not
 == (equivalent)
 != (not equivalent)

Boolean OR Operator

The Boolean or operator returns True if any one of the inputs is True else returns False.
A B A or B
True True True
True False True
False True True
False False False

Example: Python Boolean OR Operator

 Python3
# Python program to demonstrate
# or operator

a =1
b =2
c =4

ifa > b orb < c:


print(True)
else:
print(False)

ifa orb orc:


print("Atleast one number has boolean value as True")
Output
True
Atleast one number has boolean value as True
In the above example, we have used Python boolean with if statement and OR operator that
check if a is greater than b or b is smaller than c and it returns True if any of the condition is
True (b<c in the above example).

Boolean And Operator

The Boolean and operator returns False if any one of the inputs is False else returns True.
A B A and B
True True True
True False False
False True False
False False False

Example: Python Boolean And Operator

 Python3
# Python program to demonstrate
# and operator

a =0
b =2
c =4

ifa > b andb<c:


print(True)
else:
print(False)

ifa andb andc:


print("All the numbers has boolean value as True")
else:
print("Atleast one number has boolean value as False")
Output
False
Atleast one number has boolean value as False

Boolean Not Operator

The Boolean Not operator only require one argument and returns the negation of the
argument i.e. returns the True for False and False for True.
A Not A
True False
False True

Example: Python Boolean Not Operator

 Python3
# Python program to demonstrate
# not operator

a =0

ifnota:
print("Boolean value of a is False")
Output
Boolean value of a is False

Boolean == (equivalent) and != (not equivalent) Operator

Both the operators are used to compared two results. == (equivalent operator returns True
if two results are equal and != (not equivalent operator returns True if the two results are
not same.

Example: Python Boolean == (equivalent) and != (not equivalent) Operator

 Python3
# Python program to demonstrate
# equivalent an not equivalent
# operator

a =0
b =1

ifa ==0:
print(True)

ifa ==b:
print(True)

ifa !=b:
print(True)
Output
True
True

is Operator

The is keyword is used to test whether two variables belong to the same object. The test will
return True if the two objects are the same else it will return False even if the two objects
are 100% equal.

Example: Python is Operator

 Python3
# Python program to demonstrate
# is keyword

x =10
y =10

ifx isy:
print(True)
else:
print(False)

x =["a", "b", "c", "d"]


y =["a", "b", "c", "d"]

print(x isy)
Output
True
False

in Operator

in operator checks for the membership i.e. checks if the value is present in a list, tuple, range,
string, etc.

Example: in Operator
 Python3
# Python program to demonstrate
# in keyword

# Create a list
animals =["dog", "lion", "cat"]

# Check if lion in list or not


if"lion"inanimals:
print(True)
Output
True

Output Statements

Python print() function prints the message to the screen or any other standard output
device. In this article, we will cover about print() function in Python as well as it’s various
operations.
Python print() Function Syntax
Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
Parameters:
 value(s): Any value, and as many as you like. Will be converted to a string before printed
 sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than
one.Default :’ ‘
 end=’end’: (Optional) Specify what to print at the end.Default : ‘\n’
 file : (Optional) An object with a write method. Default :sys.stdout
 flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False).
Default: False
Return Type: It returns output to the screen.
Though it is not necessary to pass arguments in the print() function, it requires an empty
parenthesis at the end that tells Python to execute the function rather than calling it by
name. Now, let’s explore the optional arguments that can be used with the print() function.
Example
In this example, we have created three variables integer, string and float and we are printing
all the variables with print() function in Python.
Python

name = "John"
age = 30

print("Name:", name)
print("Age:", age)

Output

Name: John
Age: 30
How print() works in Python?
You can pass variables, strings, numbers, or other data types as one or more parameters
when using the print() function. Then, these parameters are represented as strings by their
respective str() functions. To create a single output string, the transformed strings are
concatenated with spaces between them.
In this code, we are passing two parameters name and age to the print function.
Python

name = "Alice"
age = 25

print("Hello, my name is", name, "and I am", age, "years old.")

Output

Hello, my name is Alice and I am 25 years old.

Python print() Function with Examples


Python String Literals
String literals in Python’s print statement are primarily used to format or design how a
specific string appears when printed using the print() function.
 \n: This string literal is used to add a new blank line while printing a statement.
 “”: An empty quote (“”) is used to print an empty line.
Example
This code uses \n to print the data to the new line.
Python

print("GeeksforGeeks \n is best for DSA Content.")

Output

GeeksforGeeks
is best for DSA Content.

Python “end” parameter in print()


The end keyword is used to specify the content that is to be printed at the end of the
execution of the print() function. By default, it is set to “\n”, which leads to the change of line
after the execution of print() statement.
Example
In this example, we are using print() with end and without end parameters.
Python
# This line will automatically add a new line before the
# next print statement
print ("GeeksForGeeks is the best platform for DSA content")

# This print() function ends with "**" as set in the end argument.
print ("GeeksForGeeks is the best platform for DSA content", end= "**")
print("Welcome to GFG")

Output

GeeksForGeeks is the best platform for DSA content


GeeksForGeeks is the best platform for DSA content**Welcome to GFG

Print Concatenated Strings


In this example, we are concatenating strings inside print() function in Python.
Python

print('GeeksforGeeks is a Wonderful ' + 'Website.')

Output

GeeksforGeeks is a Wonderful Website.

Output formatting
In this example, we are formatting our output to make it look more attractive by
using str.format() function.
Python

a,b,=10,1000
print('The value of a is {} and b is {}'.format(a,b))

Output

The value of a is 10 and b is 1000


Input Statements

Python input() function is used to take user input. By default, it returns the user input in
form of a string.
input() Function
Syntax:
input(prompt)
prompt [optional]: any string value to display as input message
Ex: input(“What is your name? “)
Returns: Return a string value as input by the user.
By default input() function helps in taking user input as string.
If any user wants to take input as int or float, we just need to typecast it.
Refer to all datatypes and examples from here.
Python input() Function Example
Python

# Taking input as string


color = input("What color is rose?: ")
print(color)

# Taking input as int


# Typecasting to int
n = int(input("How many roses?: "))
print(n)

# Taking input as float


# Typecasting to float
price = float(input("Price of each rose?: "))
print(price)
Output:
What color is rose?: red
red
How many roses?: 10
10
Price of each rose?: 15.50
15.5
Example 1: Taking the Name and Age of the user as input and printing it
By default, input returns a string. So the name and age will be stored as strings.
Python

# Taking name of the user as input


# and storing it name variable
name = input("Please Enter Your Name: ")

# taking age of the user as input and


# storing in into variable age
age = input("Please Enter Your Age: ")

print("Name & Age: ", name, age)


Output:
Please Enter Your Name: Rohit
Please Enter Your Age: 16
Name & Age: Rohit 16
Example 2: Taking two integers from users and adding them.
In this example, we will be looking at how to take integer input from users. To take integer
input we will be using int() along with Python input()
Python

# Taking number 1 from user as int


num1 = int(input("Please Enter First Number: "))
# Taking number 2 from user as int
num2 = int(input("Please Enter Second Number: "))

# adding num1 and num2 and storing them in


# variable addition
addition = num1 + num2

# printing
print("The sum of the two given numbers is {} ".format(addition))
Output:

Similarly, we can use float() to take two float numbers. Let’s see one more example of how to
take lists as input
Example 3: Taking Two lists as input and appending them
Taking user input as a string and splitting on each character using list() to convert into list of
characters.
Python

# Taking list1 input from user as list


list1 = list(input("Please Enter Elements of list1: "))

# Taking list2 input from user as list


list2 = list(input("Please Enter Elements of list2: "))

# appending list2 into list1 using .append function


for i in list2:
list1.append(i)

# printing list1
print(list1)
Output:
Comments

Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
programmers to understand the code very carefully. There are three types of comments in
Python –
 Single line Comments
 Multiline Comments
 Docstring Comments

Example: Comments in Python

 Python3
# Python program to demonstrate comments

# sample comment
name ="geeksforgeeks"
print(name)
Output:
geeksforgeeks
In the above example, it can be seen that comments are ignored by the interpreter during
the execution of the program.
Comments are generally used for the following purposes:
 Code Readability
 Explanation of the code or Metadata of the project
 Prevent execution of code
 To include resources
Types of Comments in Python
There are three main kinds of comments in Python. They are:
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no white spaces and
lasts till the end of the line. If the comment exceeds one line then put a hashtag on the next
line and continue the comment. Python’s single-line comments are proved useful for
supplying short explanations for variables, function declarations, and expressions. See the
following code snippet demonstrating single line comment:
Example:
 Python3
# Print “GeeksforGeeks !” to console
print("GeeksforGeeks")

Output
GeeksforGeeks
Multi-Line Comments

Python does not provide the option for multiline comments. However, there are different
ways through which we can write multiline comments.

Using Multiple Hashtags (#)

We can multiple hashtags (#) to write multiline comments in Python. Each and every line
will be considered as a single-line comment.

Example: Multiline comments using multiple hashtags (#)

 Python3

# Python program to demonstrate


# multiline comments
print("Multiline comments")

Output
Multiline comments

Using String Literals

Python ignores the string literals that are not assigned to a variable so we can use these
string literals as a comment.

Example 1:

 Python3

'This will be ignored by Python'

On executing the above code we can see that there will not be any output so we use the
strings with triple quotes(“””) as multiline comments.

Example 2: Multiline comments using string literals

 Python3
""" Python program to demonstrate

multiline comments"""

print("Multiline comments")

Output

Multiline comments
Python Docstring
Python docstring is the string literals with triple quotes that are appeared right after the
function. It is used to associate documentation that has been written with Python modules,
functions, classes, and methods. It is added right below the functions, modules, or classes to
describe what they do. In Python, the docstring is then made available via the __doc__
attribute.
Example:
 Python3
defmultiply(a, b):
"""Multiplies the value of a and b"""
returna*b

# Print the docstring of multiply function


print(multiply.__doc__)
Output:
Multiplies the value of a and b
Operators

Python Operators in general are used to perform operations on values and variables. These
are standard symbols used for the purpose of logical and arithmetic operations. In this article,
we will look into different types of Python operators.
OPERATORS: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Types of Python Operators
Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us have a quick look on all these operators one by one.


Python Arithmetic Operators
Python arithmetic operators are used to perform mathematical operations on numerical
values. These operations are Addition, Subtraction, Multiplication, Division, Modulus,
Expoents and Floor Division.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

Example

Following is an example which shows all the above operations:


a =21
b =10

# Addition
print("a + b : ", a + b)

# Subtraction
print("a - b : ", a - b)

# Multiplication
print("a * b : ", a * b)

# Division
print("a / b : ", a / b)

# Modulus
print("a % b : ", a % b)

# Exponent
print("a ** b : ", a ** b)
# Floor Division
print("a // b : ", a // b)
This produce the following result −
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Python Comparison Operators
Python comparison operators compare the values on either sides of them and decide the
relation among them. They are also called relational operators. These operators are equal, not
equal, greater than, less than, greater than or equal to and less than or equal to.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

Example

Following is an example which shows all the above comparison operations:


a =4
b =5

# Equal
print("a == b : ", a == b)

# Not Equal
print("a != b : ", a != b)

# Greater Than
print("a >b : ", a > b)

# Less Than
print("a <b : ", a < b)

# Greater Than or Equal to


print("a >= b : ", a >= b)

# Less Than or Equal to


print("a <= b : ", a <= b)
This produce the following result −
a == b : False
a != b : True
a >b : False
a <b : True
a >= b : False
a <= b : True
Python Assignment Operators
Python assignment operators are used to assign values to variables. These operators include
simple assignment operator, addition assign, subtraction assign, multiplication assign,
division and assign operators etc.

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

Example

Following is an example which shows all the above assignment operations:


# Assignment Operator
a =10

# Addition Assignment
a +=5
print("a += 5 : ", a)

# Subtraction Assignment
a -=5
print("a -= 5 : ", a)

# Multiplication Assignment
a *=5
print("a *= 5 : ", a)

# Division Assignment
a /=5
print("a /= 5 : ",a)

# Remainder Assignment
a %=3
print("a %= 3 : ", a)

# Exponent Assignment
a **=2
print("a **= 2 : ", a)

# Floor Division Assignment


a //=3
print("a //= 3 : ", a)
This produce the following result −
a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0
Python Bitwise Operators
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13;
Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
There are following Bitwise operators supported by Python language

Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits


is 1

~ Binary Ones Complement Inverts all the bits

<< Binary Left Shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off

>> Binary Right Shift Shift right by pushing copies of the


leftmost bit in from the left, and let the
rightmost bits fall off

Example

Following is an example which shows all the above bitwise operations:


a =60# 60 = 0011 1100
b =13# 13 = 0000 1101

# Binary AND
c=a&b # 12 = 0000 1100
print("a &b : ", c)

# Binary OR
c=a|b # 61 = 0011 1101
print("a | b : ", c)

# Binary XOR
c=a^b # 49 = 0011 0001
print("a ^ b : ", c)
# Binary Ones Complement
c =~a;# -61 = 1100 0011
print("~a : ", c)

# Binary Left Shift


c = a <<2;# 240 = 1111 0000
print("a <<2 : ", c)

# Binary Right Shift


c = a >>2;# 15 = 0000 1111
print("a >>2 : ", c)
This produce the following result −
a &b : 12
a | b : 61
a ^ b : 49
~a : -61
a >>2 : 240
a >>2 : 15
Python Logical Operators
There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
[ Show Example ]

Operator Description Example

and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.

or Logical OR If any of the two operands are non- (a or b) is true.


zero then condition becomes true.

not Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.

Python Membership Operators


Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
[ Show Example ]

Operator Description Example


in Evaluates to true if it finds a variable
x in y, here in results in a 1 if x is
in the specified sequence and false
a member of sequence y.
otherwise.

not in Evaluates to true if it does not finds a x not in y, here not in results in a
variable in the specified sequence 1 if x is not a member of
and false otherwise. sequence y.

Python Identity Operators


Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]

Operator Description Example

is Evaluates to true if the variables on either


x is y, here is results in
side of the operator point to the same object
1 if id(x) equals id(y).
and false otherwise.

is not Evaluates to false if the variables on either x is not y, here is


side of the operator point to the same object not results in 1 if id(x)
and true otherwise. is not equal to id(y).

Python Operators Precedence


The following table lists all operators from highest precedence to lowest.
[ Show Example ]

Sr.No. Operator & Description

1 **
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last two are +@
and -@)

3 * / % //
Multiply, divide, modulo and floor division
4 +-
Addition and subtraction

5 >><<
Right and left bitwise shift

6 &
Bitwise 'AND'

7 ^|
Bitwise exclusive `OR' and regular `OR'

8 <= <>>=
Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **=
Assignment operators

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators

Expressions

An Expression is a sequence or combination of values, variables, operators and function calls


that always produces or returns a result value.Example: x = 5, y = 3, z = x + y

In the above example x, y and z are variables, 5 and 3 are values, = and + are operators.
So, the first combination x = 5 is an expression, the second combination y = 3 is an another
expression and at last, z = x + y is also an expression.

– An Expression always evaluates (calculate) to itself.

Types of Expression in Python

1. Constant Expressions

A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a
value that cannot be changed after its initialization.

Example :
x = 10 + 15

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)
Output :
The value of x is: 25

2. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes


parenthesis is known as an arithmetic expression. The result of an arithmetic expression is
also a numeric value just like the constant expression discussed above. Before getting into the
example of an arithmetic expression in Python, let us first know about the various operators
used in the arithmetic expressions.

Operator Syntax Working

+ x+y Addition or summation of x and y.

- x-y Subtraction of y from x.

x xxy Multiplication or product of x and y.

/ x/y Division of x and y.

// x // y Quotient when x is divided by y.

% x%y Remainder when x is divided by y.

** x ** y Exponent (x to the power of y).

Example :
x = 10
y=5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)
print("The division of x and y is: ", division)
print("x to the power y is: ", power)
Output :
The sum of x and y is: 15
The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000

3. Integral Expressions

An integral expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). An integral expression always produces an integer
value as a resultant.

Example :
x = 10 # an integer number
y = 5.0 # a floating point number

# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)

print("The sum of x and y is: ", result)


Output :
The sum of x and y is: 15

4. Floating Expressions

A floating expression in Python is used for computations and type conversion


(integer to float, a string to integer, etc.). A floating expression always produces a floating-
point number as a resultant.

Example:
x = 10 # an integer number
y = 5.0 # a floating-point number

# we need to convert the integer number into a floating-point number or vice versa for
summation.
result = float(x) + y

print("The sum of x and y is: ", result)


Output :
The sum of x and y is: 15.0
5. Relational Expressions

A relational expression in Python can be considered as a combination of two or more


arithmetic expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in Python (i.e.
> ,< , >= , <=)(i.e.>,<,>=,<=).

A relational operator produces a boolean result so they are also known as Boolean
Expressions.

For example :
10 + 15 > 2010+15>20

In this example, first, the arithmetic expressions (i.e. 10 + 1510+15 and 2020) are evaluated,
and then the results are used for further comparison.

Example :
a = 25
b = 14
c = 48
d = 45

# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output :
Type: <class 'bool'>
The result of the expression is: False

6. Logical Expressions

As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.

Operator Syntax Working

and xx and yy The expression return True if both xx and yy are true, else it
returns False.

or xx or yy The expression return True if at least one of xx or yy is True.

not not xx The expression returns True if the condition of xx is False.

Note :
In the table specified above, xx and yy can be values or another expression as well.

Example :
from operator import and_
x = (10 == 9)
y = (7 > 5)

and_result = x and y
or_result = x or y
not_x = not x

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)
Output :
The result of x and y is: False
The result of x or y is: True
The not of x is: True

7. Bitwise Expressions

The expression in which the operation or computation is performed at the bit level is known
as a bitwise expression in Python. The bitwise expression contains the bitwise operators.

Example :
x = 25
left_shift = x << 1
right_shift = x >> 1

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)
Output :
One right shift of x results: 12
One left shift of x results: 50

8. Combinational Expressions

As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.

Example :
x = 25
y = 35

result = x + (y << 1)

print("Result obtained : ", result)


Output :
Result obtained: 95
Whenever there are multiple expressions involved then the expressions are resolved based on
their precedence or priority. Let us learn about the precedence of various operators in the
following section.

Multiple Operators in Expression (Operator Precedence) ?

The operator precedence is used to define the operator's priority i.e. which operator will be
executed first. The operator precedence is similar to the BODMAS rule that we learned in
mathematics. Refer to the list specified below for operator precedence.

Precedence Operator Name


1. ()[]{} Parenthesis
2. ** Exponentiation
3. -value , +value , ~value Unary plus or minus, complement
4. / * // % Multiply, Divide, Modulo
5. +– Addition & Subtraction
6. >><< Shift Operators
7. & Bitwise AND
8. ^ Bitwise XOR
9. pipe symbol Bitwise OR
10. >= <= >< Comparison Operators
11. == != Equality Operators
12. = += -= /= *= Assignment Operators
13. is, is not, in, not in Identity and membership operators
14. and, or, not Logical Operators
Let us take an example to understand the precedence better :
x = 12
y = 14
z = 16

result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)

result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)

result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)
Output :
Result of 'x + y + z' is: 236
Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236
Difference between Statements and Expressions in Python

We have earlier discussed statement expression in Python, let us learn the differences
between them.

Statement in Python Expression in Python


A statement in Python is used for The expression in Python produces some value
creating variables or for displaying or result after being interpreted by the Python
values. interpreter.
A statement in Python is not An expression in Python is evaluated for some
evaluated for some results. results.
The execution of a statement The expression evaluation does not result in
changes the state of the variable. any state change.
A statement can be an expression. An expression is not a statement.
Example : x = 3x=3. Example: x = 3 + 6x=3+6.
Output : 33 Output : 99
Type conversions

Python defines type conversion functions to directly convert one data type to another which
is useful in day-to-day and competitive programming. This article is aimed at providing
information about certain conversion functions.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Let’s discuss them in detail.
Implicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter automatically
converts one data type to another without any user involvement. To get a more clear view of
the topic see the below examples.
Example:
 Python3
x =10

print("x is of type:",type(x))

y =10.6
print("y is of type:",type(y))

z =x +y

print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
As we can see the data type of ‘z’ got automatically changed to the “float” type while one
variable x is of integer type while the other variable y is of float type. The reason for the float
value not being converted into an integer instead is due to type promotion that allows
performing operations by converting data into a wider-sized data type without any loss of
information. This is a simple case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per
their requirement. With explicit type conversion, there is a risk of data loss since we are
forcing an expression to be changed in some specific data type. Various forms of explicit
type conversion are explained below:

1. int(a, base): This function converts any data type to integer. ‘Base’ specifies the base in
which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
 Python3

# Python code to demonstrate Type conversion


# using int(), float()
# initializing string
s ="10010"
# printing string converting to int base 2
c =int(s,2)
print("After converting to integer base 2 : ", end="")
print(c)
# printing string converting to float
e =float(s)
print("After converting to float : ", end="")
print(e)

Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.

 Python3

# Python code to demonstrate Type conversion

# using ord(), hex(), oct()

# initializing integer
s ='4'

# printing character converting to integer

c =ord(s)

print("After converting character to integer : ",end="")

print(c)

# printing integer converting to hexadecimal string

c =hex(56)

print("After converting 56 to hexadecimal string : ",end="")

print(c)

# printing integer converting to octal string

c =oct(56)

print("After converting 56 to octal string : ",end="")

print(c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.

 Python3

# Python code to demonstrate Type conversion

# using tuple(), set(), list()

# initializing string

s ='geeks'

# printing string converting to tuple

c =tuple(s)

print("After converting string to tuple : ",end="")


print(c)

# printing string converting to set

c =set(s)

print("After converting string to set : ",end="")

print(c)

# printing string converting to list

c =list(s)

print("After converting string to list : ",end="")

print(c)
Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag)
number.

 Python3

# Python code to demonstrate Type conversion

# using dict(), complex(), str()

# initializing integers

a =1

b =2

# initializing tuple

tup =(('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number

c =complex(1,2)

print("After converting integer to complex number : ",end="")

print(c)
# printing integer converting to string

c =str(a)

print("After converting integer to string : ",end="")

print(c)

# printing tuple converting to expression dictionary

c =dict(tup)

print("After converting tuple to dictionary : ",end="")

print(c)
Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
12. chr(number): This function converts number to its corresponding ASCII character.

 Python3

# Convert ASCII value to characters

a =chr(76)

b =chr(77

print(a)

print(b)

Output:

M
Defining and Processing Arrays – Array methods.

An array is a collection of items stored at contiguous memory locations. The idea is to store
multiple items of the same type together. This makes it easier to calculate the position of
each element by simply adding an offset to a base value, i.e., the memory location of the first
element of the array (generally denoted by the name of the array).
To get a detailed explanation of Python Array go through the Python Self Paced course , this
course offers you a complete fundamental of Python Array.
Create an Array in Python
Array in Python can be created by importing an array
module. array( data_type , value_list ) is used to create array in Python with data type and
value list specified in its arguments.
In below code Python create array : one of integers and one of doubles . It then prints the
contents of each array to the console.
Python

import array as arr


a = arr.array('i', [1, 2, 3])
print("The new created array is : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("\nThe new created array is : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")

Output

The new created array is : 1 2 3

The new created array is : 2.5 3.2 3.3


Complexities for Creation of Arrays:
Time Complexity: O(n)
Auxiliary Space: O(n)
Some of the data types are mentioned below which will help in create array in Python 3.8 of
different data types.
Now we will see how to use array in Python 3.8 with example.
Adding Elements to an Array
Elements can be added to the Python Array by using built-in insert() function. Insert is used
to insert one or more data elements into an array. Based on the requirement, a new element
can be added at the beginning, end, or any given index of array. append() is also used to add
the value mentioned in its arguments at the end of the Python array.
Below, code first imports the array module as Python import array as arr . Then, it creates
an array of integers named a with elements [1, 2, 3] . In below code Python print array as
array is printed before and after inserting the integer 4 at index 1. Similarly, an array of
doubles named b with elements [2.5, 3.2, 3.3] is created and printed before and after
appending the double 4.4 to the array.
Python

import array as arr


a = arr.array('i', [1, 2, 3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(a[i], end=" ")
print()
a.insert(1, 4)
print("Array after insertion : ", end=" ")
for i in (a):
print(i, end=" ")
print()
b = arr.array('d', [2.5, 3.2, 3.3])
print("Array before insertion : ", end=" ")
for i in range(0, 3):
print(b[i], end=" ")
print()
b.append(4.4)
print("Array after insertion : ", end=" ")
for i in (b):
print(i, end=" ")
print()

Output

Array before insertion : 1 2 3


Array after insertion : 1 4 2 3
Array before insertion : 2.5 3.2 3.3
Array after insertion : 2.5 3.2 3.3 4.4
Complexities for Adding elements to the Arrays
Time Complexity: O(1)/O(n) ( O(1) – for inserting elements at the end of the array, O(n) –
for inserting elements at the beginning of the array and to the full array
Auxiliary Space: O(1)
Accessing Elements from the Array
In order to access the array items refer to the index number. Use the index operator [ ] to
access an item in a array in Python. The index must be an integer.
Below, code shows first how to Python import array and use of indexing to access elements
in arrays. The a[0] expression accesses the first element of the array a , which is 1.
The a[3] expression accesses the fourth element of the array a , which is 4. Similarly,
the b[1] expression accesses the second element of the array b , which is 3.2, and
the b[2] expression accesses the third element of the array b , which is 3.3.
Python

import array as arr


a = arr.array('i', [1, 2, 3, 4, 5, 6])
print("Access element is: ", a[0])
print("Access element is: ", a[3])
b = arr.array('d', [2.5, 3.2, 3.3])
print("Access element is: ", b[1])
print("Access element is: ", b[2])

Output

Access element is: 1


Access element is: 4
Access element is: 3.2
Access element is: 3.3
Complexities for accessing elements in the Arrays
Time Complexity: O(1)
Auxiliary Space: O(1)
Removing Elements from the Array
Elements can be removed from the Python array by using built-in remove() function but an
Error arises if element doesn’t exist in the set. Remove() method only removes one element
at a time, to remove range of elements, iterator is used. pop() function can also be used to
remove and return an element from the array, but by default it removes only the last
element of the array, to remove element from a specific position of the array, index of the
element is passed as an argument to the pop() method.
Note – Remove method in List will only remove the first occurrence of the searched element.
Below, code shows how to Python import array, how to create, print, remove elements from,
and access elements of an array in Python. It imports the array module, which is used to
work with arrays. It creates an array of integers in and Python print arrays or prints the
original array. It then removes an element from the array and prints the modified array.
Finally, it removes all occurrences of a specific element from the array and prints the
updated array
Python

import array
arr = array.array('i', [1, 2, 3, 1, 5])
print("The new created array is : ", end="")
for i in range(0, 5):
print(arr[i], end=" ")

print("\r")
print("The popped element is : ", end="")
print(arr.pop(2))
print("The array after popping is : ", end="")
for i in range(0, 4):
print(arr[i], end=" ")

print("\r")
arr.remove(1)
print("The array after removing is : ", end="")
for i in range(0, 3):
print(arr[i], end=" ")

Output

The new created array is : 1 2 3 1 5


The popped element is : 3
The array after popping is : 1 2 1 5
The array after removing is : 2 1 5
Complexities for Removing elements in the Arrays
Time Complexity: O(1)/O(n) ( O(1) – for removing elements at the end of the array, O(n) –
for removing elements at the beginning of the Python create array and to the full array
Auxiliary Space: O(1)
Slicing of an Array
In Python array, there are multiple ways to print the whole array with all the elements, but
to print a specific range of elements from the array, we use Slice operation . Slice operation
is performed on array with the use of colon(:). To print elements from beginning to a range
use [:Index], to print elements from end use [:-Index], to print elements from specific Index
till the end use [Index:], to print elements within a range, use [Start Index:End Index] and to
print whole List with the use of slicing operation, use [:]. Further, to print whole array in
reverse order, use [::-1].

This code employs slicing to extract elements or subarrays from an array. It starts with an
initial array of integers and creates an array from the list. The code slices the array to extract
elements from index 3 to 8, from index 5 to the end, and the entire array and In below code
Python print array as The sliced arrays are then printed to demonstrate the slicing
operations.
Python

import array as arr


l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

a = arr.array('i', l)
print("Initial Array: ")
for i in (a):
print(i, end=" ")
Sliced_array = a[3:8]
print("\nSlicing elements in a range 3-8: ")
print(Sliced_array)
Sliced_array = a[5:]
print("\nElements sliced from 5th "
"element till the end: ")
print(Sliced_array)
Sliced_array = a[:]
print("\nPrinting all elements using slice operation: ")
print(Sliced_array)

Output

Initial Array:
1 2 3 4 5 6 7 8 9 10
Slicing elements in a range 3-8:
array('i', [4, 5, 6, 7, 8])

Elements sliced from 5th element till the end:


array('i', [6, 7, 8, 9, 10])

Printing all elements...


Searching Element in an Array
In order to search an element in the array we use a python in-built index() method. This
function returns the index of the first occurrence of value mentioned in arguments.
Example: The code demonstrates how to create array in Python, print its elements, and find
the indices of specific elements. It imports the array module, creates an array of integers,
prints the array using a for loop, and then uses the index() method to find the indices of the
first occurrences of the integers 2 and 1.
Python

import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("The new created array is : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")

print("\r")
print("The index of 1st occurrence of 2 is : ", end="")
print(arr.index(2))
print("The index of 1st occurrence of 1 is : ", end="")
print(arr.index(1))

Output

The new created array is : 1 2 3 1 2 5


The index of 1st occurrence of 2 is : 1
The index of 1st occurrence of 1 is : 0
Complexities for searching elements in the Arrays
Time Complexity: O(n)
Auxiliary Space: O(1)
Updating Elements in an Array
In order to update an element in the array we simply reassign a new value to the desired
index we want to update.
Example: This code illustrates the functionality of modifying elements within an array using
indexing. It imports the array module, creates an array of integers, and prints the initial
array. Then, it modifies two elements of the array at specific indexes and prints the updated
array. This serves to demonstrate how indexing allows for dynamic manipulation of array
contents.
Python

import array
arr = array.array('i', [1, 2, 3, 1, 2, 5])
print("Array before updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print("\r")
arr[2] = 6
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")
print()
arr[4] = 8
print("Array after updation : ", end="")
for i in range(0, 6):
print(arr[i], end=" ")

Output

Array before updation : 1 2 3 1 2 5


Array after updation : 1 2 6 1 2 5
Array after updation : 1 2 6 1 8 5
Complexities for updating elements in the Arrays
Time Complexity: O(1)
Auxiliary Space: O(1)

You might also like