Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
8 views

Python SIM

Uploaded by

rishavvraj.in
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python SIM

Uploaded by

rishavvraj.in
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

Module-1

What is Python?
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was
mainly developed for emphasis on code readability, and its syntax allows programmers to
express concepts in fewer lines of code. Python is a programming language that lets you work
quickly and integrate systems more efficiently.

Python Versions:
There are two major Python versions- Python 2 and Python 3.
• On 16 October 2000, Python 2.0 was released with many new features.
• On 3rd December 2008, Python 3.0 was released with more testing and includes new
features.
Why use Python?
1. Python is object-oriented: Structure supports such concepts as polymorphism, operation
overloading and multiple inheritance.
2. Indentation: Indentation is one of the greatest feature in python
3. It’s free (open source): Downloading python and installing python is free and easy
4. It’s Powerful:
● Dynamic typing
● Built-in types and tools
● Library utilities
● Third party utilities (e.g. Numeric, NumPy, sciPy)
● Automatic memory management
5. It’s Portable:
● Python runs virtually every major platform used today
● As long as you have a compaitable python interpreter installed, python programs will run
in exactly the same manner, irrespective of platform.
6. It’s easy to use and learn:
● No intermediate compile
● Python Programs are compiled automatically to an intermediate form called byte code,
which the interpreter then reads.
● This gives python the development speed of an interpreter without the performance loss
inherent in purely interpreted languages.
● Structure and syntax are pretty intuitive and easy to grasp.
7. Interpreted Language: Python is processed at runtime by python Interpreter
8. Interactive Programming Language: Users can interact with the python interpreter directly
for writing the programs
9. Straight forward syntax: The formation of python syntax is simple and straight forward
which also makes it popular.
Difference between scripting language and programming language:

Applications of Python:
● Web Development: Python is used to build web applications and websites using
popular frameworks like Django and Flask. These frameworks simplify the development
of web applications, making it easier to handle tasks such as routing, authentication and
database interactions.
● Data Analysis and Visualization: Python is widely used in data analysis and
visualization. Libraries like Pandas, NumPy and Matplotlib provide powerful tools for data
manipulation, analysis, and the creation of informative charts and graphs. Python is a
go-to language for data scientists and analysts.
● Machine Learning and Artificial Intelligence: Python has become the de facto
language for machine learning and artificial intelligence. Libraries like TensorFlow, Keras,
PyTorch and scikit-learn make it easy to build and train machine learning models for
tasks like image recognition, natural language processing and predictive analytics.
● Scientific Computing: Python is used in various scientific disciplines for simulations,
data analysis and visualization. Libraries like SciPy, SymPy and matplotlib are essential
tools for researchers and scientists in fields such as physics, biology, chemistry and
various types of engineering.
● Automation and Scripting: Python’s simplicity and readability make it an excellent
choice for automation and scripting tasks. It can be used to automate repetitive tasks,
manage files and directories, as well as to interact with operating system functions.
● Game Development: Python is used in game development, primarily for creating 2D
games. Libraries like Pygame provide game developers with the tools needed to build
interactive games and simulations.
● Web Scraping and Data Extraction: Python is widely used for web scraping and data
extraction. Developers use libraries like BeautifulSoup and Scrapy to extract data from
websites, which can be used for various purposes, including data analysis, market
research and content aggregation.

Number System:
The technique to represent and work with numbers is called number system. Decimal number
system is the most common number system. Other popular number systems include binary
number system, octal number system, hexadecimal number system, etc.

Binary Number System:


The easiest way to vary instructions through electric signals is two-state system – on and off. On
is represented as 1 and off as 0, though 0 is not actually no signal but signal at a lower voltage.
The number system having just these two digits – 0 and 1 – is called binary number system.

Each binary digit is also called a bit. Binary number system is also positional value system,
where each digit has a value expressed in powers of 2, as displayed here.

In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit
is called most significant bit (MSB).

And decimal equivalent of this number is sum of product of each digit with its positional value.

110102 = 1×24 + 1×23 + 0×22 + 1×21 + 0×20


= 16 + 8 + 0 + 2 + 0

= 2610

Computer memory is measured in terms of how many bits it can store. Here is a chart for
memory capacity conversion.

​ 1 byte (B) = 8 bits


​ 1 Kilobytes (KB) = 1024 bytes
​ 1 Megabyte (MB) = 1024 KB
​ 1 Gigabyte (GB) = 1024 MB
​ 1 Terabyte (TB) = 1024 GB
​ 1 Exabyte (EB) = 1024 PB
​ 1 Zettabyte = 1024 EB
​ 1 Yottabyte (YB) = 1024 ZB

Octal Number System:


Octal number system has eight digits – 0, 1, 2, 3, 4, 5, 6 and 7. Octal number system is also a
positional value system with where each digit has its value expressed in powers of 8, as shown
here −

Decimal equivalent of any octal number is sum of product of each digit with its positional value.

7268 = 7×82 + 2×81 + 6×80

= 448 + 16 + 6

= 47010

Number System Relationship:


The following table depicts the relationship between decimal, binary, octal and hexadecimal
number systems.

DECIMAL OCTAL BINARY

0 0 0000

1 1 0001
2 2 0010

3 3 0011

4 4 0100

5 5 0101

6 6 0110

7 7 0111

8 10 1000

9 11 1001

10 12 1010

11 13 1011

12 14 1100

13 15 1101

14 16 1110

15 17 1111

Links for MCQs with solutions: (octal,binary,decimal respectively)


https://testbook.com/objective-questions/mcq-on-octal-number-system--5eea6a0d39140f30f369
e259
https://testbook.com/objective-questions/mcq-on-binary-number-system--5eea6a0d39140f30f36
9e257
https://testbook.com/objective-questions/mcq-on-decimal-number-system--5eea6a0d39140f30f3
69e258

Literals:
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 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 to demonstrate their usage.
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:
● String literals
● Character literal
● Numeric literals
● Boolean literals
● Literal Collections
● Special literals

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.

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

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

# 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 ]

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.

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:
● List literals
● Tuple literals
● Dict literals
● 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.

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.

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.

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

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


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

print(vowels)
print(fruits)
Output

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


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

Python Special literal


Python contains one special literal (None). ‘None’ is used to define a null variable. If ‘None’ is
compared with anything else other than a ‘None’, it will return false.

water_remain = None
print(water_remain)
Output

None

Variables:
Python Variable is containers that store values. Python is not “statically typed”. We do not need
to declare variables before using them or declare their type. A variable is created the moment
we first assign a value to it. A Python variable is a name given to a memory location. It is the
basic unit of storage in a program.

Example of Variable in Python


An Example of a Variable in Python is a representational name that serves as a pointer to an
object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s
terms, we can say that Variable in Python is containers that store values.

Here we have stored “Geeksforgeeks” in a var which is variable, and when we call its name the
stored information will get printed.
Var = "Geeksforgeeks"
print(Var)
Output:
Geeksforgeeks

Notes:
● The value stored in a variable can be changed during program execution.
● A Variables in Python is only a name given to a memory location, all the operations done
on the variable effects that memory location.
● Rules for Python variables
● A Python variable name must start with a letter or the underscore character.
● A Python variable name cannot start with a number.
● A Python variable name can only contain alpha-numeric characters and underscores
(A-z, 0-9, and _ ).
● Variable in Python names are case-sensitive (name, Name, and NAME are three
different variables).
● The reserved words(keywords) in Python cannot be used to name the variable in
Python.
Example
# valid variable name
geeks = 1
Geeks = 2
Ge_e_ks = 5
_geeks = 6
geeks_ = 7
_GEEKS_ = 8

print(geeks, Geeks, Ge_e_ks)


print(_geeks, geeks_, _GEEKS_)
Output:

125
678

Variables Assignment in Python


Here, we have assigned a number, a floating point number, and a string to a variable such as
age, salary, and name.

# An integer assignment
age = 45

# A floating point
salary = 1456.8
# A string
name = "John"

print(age)
print(salary)
print(name)
Output:

45
1456.8
John

Declaration and Initialization of Variables


Let’s see how to declare the variable and print the variable.

Python3

# declaring the var


Number = 100

# display
print( Number)
Output:
100

Redeclaring variables in Python


We can re-declare the Python variable once we have declared the variable already.

Python3

# declaring the var


Number = 100

# display
print("Before declare: ", Number)

# re-declare the var


Number = 120.3

print("After re-declare:", Number)


Output:

Before declare: 100


After re-declare: 120.3

Python Assign Values to Multiple Variables


Also, Python allows assigning a single value to several variables simultaneously with “=”
operators.
For example:

Python3

a = b = c = 10

print(a)
print(b)
print(c)
Output:

10
10
10

Assigning different values to multiple variables


Python allows adding different values in a single line with “,” operators.

Python3

a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)
print(b)
print(c)
Output:

1
20.2
GeeksforGeeks

Can we use the same name for different types?


If we use the same name, the variable starts referring to a new value and type.

Python3

a = 10
a = "GeeksforGeeks"
print(a)
Output:

GeeksforGeeks

How does + operator work with variables?


The Python plus operator + provides a convenient way to add a value if it is a number and
concatenate if it is a string. If a variable is already created it assigns the new value back to the
same variable.

Python3

a = 10
b = 20
print(a+b)

a = "Geeksfor"
b = "Geeks"
print(a+b)
Output
30
GeeksforGeeks

Can we use + for different Datatypes also?


No use for different types would produce an error.

Python3

a = 10
b = "Geeks"
print(a+b)
Output :

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Global and Local Python Variables


Local variables in Python are the ones that are defined and declared inside a function. We can
not call this variable outside the function.

Python3

# This function uses global variable s


def f():
s = "Welcome geeks"
print(s)
f()
Output:

Welcome geeks
Global variables in Python are the ones that are defined and declared outside a function, and
we need to use them inside a function.

Python3

# This function has a variable with


# name same as s.
def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
Output:

I love Geeksforgeeks

Global keyword in Python


Python global is a keyword that allows a user to modify a variable outside of the current scope.
It is used to create global variables from a non-global scope i.e inside a function. Global
keyword is used inside a function only when we want to do assignments or when we want to
change a variable. Global is not needed for printing and accessing.

Rules of global keyword


● If a variable is assigned a value anywhere within the function’s body, it’s assumed to be
local unless explicitly declared as global.
● Variables that are only referenced inside a function are implicitly global.
● We use a global in Python to use a global variable inside a function.
● There is no need to use a global keyword in Python outside a function.
Example:

Python program to modify a global value inside a function.

Python3

x = 15

def change():
# using a global keyword
global x

# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)
Output:

Value of x inside a function : 20


Value of x outside a function : 20

Variable Types in Python


Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in
Python programming, data types are actually classes and variables are instances (object) of
these classes.

Built-in Python Data types are:


● Numeric
● Text Type
● Sequence Type (Python list, Python tuple, Python range)
● Boolean
● Set
● Dictionary
Example:

In this example, we have shown different examples of Built-in data types in Python.

Python3
# numberic
var = 123
print("Numeric data : ", var)

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

# Boolean
print(type(True))
print(type(False))

# Creating a Set with


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

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

Output:
Numeric data : 123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>

Set with the use of String:


{'r', 'G', 'e', 'k', 'o', 's', 'F'}

Dictionary with the use of Integer Keys:


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

Object Reference in Python


Let us assign a variable x to value 5.

x=5
Object References
Another variable is y to the variable x.
y=x

Object References in Python

When Python looks at the first statement, what it does is that, first, it creates an object to
represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to
this new object 5. The second line causes Python to create the variable y, and it is not assigned
with x, rather it is made to reference that object that x does. The net effect is that the variables x
and y wind up referencing the same object. This situation, with multiple names referencing the
same object, is called a Shared Reference in Python.
Now, if we write:

x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x reference this new object.

Python Variable

Now if we assign the new value in Y, then the previous object refers to the garbage values.

y = "Computer"

Python3

# Python program to show that the variables with a value


# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Computer Science Student

class CSStudent:

# Class Variable
stream = 'cse'

# The init method or constructor


def __init__(self, roll):

# Instance Variable
self.roll = roll

# Objects of CSStudent class


a = CSStudent(101)
b = CSStudent(102)

print(a.stream) # prints "cse"


print(b.stream) # prints "cse"
print(a.roll) # prints 101

# Class variables can be accessed using class


# name also
print(CSStudent.stream) # prints "cse"
Output
cse
cse
101
cse

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 instances (object) of
these classes. The following are the standard or built-in data types in Python:

● Numeric
● Sequence Type
● Boolean
● Set
● Dictionary
● Binary Types( memoryview, bytearray, bytes)

What is Python type() Function?


To define the values ​of various data types and check their data types we use the type() function.
Consider the following examples.

This code assigns variable ‘x' different values of various data types in Python. It covers string,
integer, float, complex, list, tuple, range, dictionary, set, frozenset, boolean, bytes, bytearray,
memoryview, and the special value ‘None' successively. Each assignment replaces the previous
value, making ‘x' take on the data type and value of the most recent assignment.

x = "Hello World"
x = 50
x = 60.5
x = 3j
x = ["geeks", "for", "geeks"]
x = ("geeks", "for", "geeks")
x = range(10)
x = {"name": "Suraj", "age": 24}
x = {"geeks", "for", "geeks"}
x = frozenset({"geeks", "for", "geeks"})
x = True
x = b"Geeks"
x = bytearray(4)
x = memoryview(bytes(6))
x = None

Numeric Data Types in Python


The numeric data type in Python represents the data that has a numeric value. A numeric value
can be an integer, a floating number, or even a complex number. These values are defined as
Python int, Python float, and Python complex classes in Python.

Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by a complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.

Example: This code demonstrates how to determine the data type of variables in Python using
the type() function. It prints the data types of three variables: a (integer), b (float), and c
(complex). The output shows the respective data types for each variable.

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 Data Type in Python


The sequence Data Type in Python is the ordered collection of similar or different data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are
several sequence types in Python –

● Python String
● Python List
● Python Tuple
String Data Type
Strings in Python are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote, or triple-quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.

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

Example: This Python code showcases various string creation methods. It uses single quotes,
double quotes, and triple quotes to create strings with different content and includes a multiline
string. The code also demonstrates printing the strings and checking their data types.

String1 = 'Welcome to the Geeks World'


print("String with the use of Single Quotes: ")
print(String1)
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
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))

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

Example: This Python code demonstrates how to work with a string named ‘String1'. It initializes
the string with “GeeksForGeeks” and prints it. It then showcases how to access the first
character (“G”) using an index of 0 and the last character (“s”) using a negative index of -1.

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
print("\nFirst character of String is: ")
print(String1[0])
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
Note – To know more about strings, refer to Python String.

List Data Type


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

Creating List in Python

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

Example: This Python code demonstrates list creation and manipulation. It starts with an empty
list and prints it. It creates a list containing a single string element and prints it. It creates a list
with multiple string elements and prints selected elements from the list. It creates a
multi-dimensional list (a list of lists) and prints it. The code showcases various ways to work with
lists, including single and multi-dimensional lists(nested lists).

List = []
print("Initial blank List: ")
print(List)
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
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']]

Python Access List Items

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.

List = ["Geeks", "For", "Geeks"]


print("Accessing element from the list")
print(List[0])
print(List[2])
print("Accessing element using negative indexing")
print(List[-1])
print(List[-3])
Output:

Accessing element from the list


Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks
Note – To know more about Lists, refer to Python List.

Tuple Data Type


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

Creating a Tuple in Python


In Python, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number
of elements and of any datatype (like strings, integers, lists, 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.

Example: This Python code demonstrates different methods of creating and working with tuples.
It starts with an empty tuple and prints it. It creates a tuple containing string elements and prints
it. It converts a list into a tuple and prints the result. It creates a tuple from a string using the
tuple() function.It forms a tuple with nested tuples and displays the result.

Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
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 – The creation of a Python tuple without the use of parentheses is known as Tuple
Packing.

Access Tuple Items


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.

The code reates a tuple named ‘tuple1′ with five elements: 1, 2, 3, 4, and 5. Then it prints the
first, last, and third last elements of the tuple using indexing.

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


print("First element of tuple")
print(tuple1[0])
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
Note – To know more about tuples, refer to Python Tuples.

Boolean Data Type in Python


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

Example: The first two lines will print the type of the boolean values True and False, which is
<class 'bool'>.The third line will cause an error, because true is not a valid keyword in Python.
Python is case-sensitive, which means it distinguishes between uppercase and lowercase
letters. You need to capitalize the first letter of true to make it a boolean value.

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 Data Type in Python


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

Create a Set in Python


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 a ‘comma’. The type of elements in a
set need not be the same, various mixed-up data type values can also be passed to the set.

Example: The code is an example of how to create sets using different types of values, such as
strings, lists, and mixed values
set1 = set()
print("Initial blank Set: ")
print(set1)
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
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'}

Access Set Items


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 the keyword.

Example: This Python code creates a set named set1 with the values "Geeks", "For" and
"Geeks" . The code then prints the initial set, the elements of the set in a loop, and checks if the
value "Geeks" is in the set using the ‘in' operator

set1 = set(["Geeks", "For", "Geeks"])


print("\nInitial set")
print(set1)
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}

Elements of set:
Geeks For

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

Dictionary Data Type in Python


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

Create a Dictionary in Python


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. The dictionary can also be created by
the built-in function dict(). An empty dictionary can be created by just placing it in curly braces{}.
Note – Dictionary keys are case sensitive, the same name but different cases of Key will be
treated distinctly.

Example: This code creates and prints a variety of dictionaries. The first dictionary is empty. The
second dictionary has integer keys and string values. The third dictionary has mixed keys, with
one string key and one integer key. The fourth dictionary is created using the dict() function, and
the fifth dictionary is created using the [(key, value)] syntax

Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
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 Key-value in 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.

Example: The code in Python is used to access elements in a dictionary. Here’s what it does, It
creates a dictionary Dict with keys and values as {1: 'Geeks', 'name': 'For', 3: 'Geeks'}. It prints
the value of the element with the key 'name', which is 'For'. It prints the value of the element with
the key 3, which is 'Geeks'.

Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}


print("Accessing a element using key:")
print(Dict['name'])
print("Accessing a element using get:")
print(Dict.get(3))
Output:

Accessing a element using key:


For
Accessing a element using get:
Geeks

Operators:
Control Structures:
There are situations in real life when we need to make some decisions and
based on these decisions, we decide what we should do next. Similar
situations arise in programming also where we need to make some decisions
and based on these decisions we will execute the next block of code.
Conditional statements in Python languages decide the direction(Control
Flow) of the flow of program execution.

Types of Control Flow in Python


Python control flow statements are as follows:

1. The if statement

2. The if-else statement

3. The nested-if statement

4. The if-elif-else ladder

Python if statement
The if statement is the most simple decision-making statement. It is used to
decide whether a certain statement or block of statements will be executed
or not.

Syntax:
if condition:
# Statements to execute if
# condition is true

Here, the condition after evaluation will be either true or false. if the
statement accepts boolean values – if the value is true then it will execute
the block of statements below it otherwise not.

As we know, python uses indentation to identify a block. So the block under


an if statement will be identified as shown in the below example:
if condition:
statement1
statement2
# Here if the condition is true, if block
# will consider only statement1 to be inside
# its block.

Flowchart of Python if statement


Flowchart of Python if statement

Example of Python if Statement

As the condition present in the if statement is false. So, the block below the
if statement is executed.

Python3

# python program to illustrate If statement

i = 10

if (i > 15):

print("10 is less than 15")

print("I am Not in if")

Output:
I am Not in if

Python If-Else Statement


The if statement alone tells us that if a condition is true it will execute a
block of statements and if the condition is false it won’t. But if we want to do
something else if the condition is false, we can use the else statement with if
statement to execute a block of code when the if condition is false.

Syntax of Python If-Else:


if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Flowchart of Python if-else statement


Flowchart of Python is-else statement

Using Python if-else statement

The block of code following the else statement is executed as the condition
present in the if statement is false after calling the statement which is not in
the block(without spaces).

Python3

# python program to illustrate If else


statement

#!/usr/bin/python

i = 20

if (i < 15):

print("i is smaller than 15")

print("i'm in if Block")
else:

print("i is greater than 15")

print("i'm in else Block")

print("i'm not in if and not in else Block")

Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

Python if else statement in a List Comprehension

In this example, we are using an if statement in a list comprehension with the


condition that if the element of the list is odd then its digit sum will be
stored else not.

Python3
# Explicit function

def digitSum(n):

dsum = 0

for ele in str(n):

dsum += int(ele)

return dsum

# Initializing list

List = [367, 111, 562, 945, 6726, 873]


# Using the function on odd elements of the
list

newList = [digitSum(i) for i in List if i & 1]

# Displaying new list

print(newList)

Output :
[16, 3, 18, 18]

Nested-If Statement in Python


A nested if is an if statement that is the target of another if statement.
Nested if statements mean an if statement inside another if statement. Yes,
Python allows us to nest if statements within if statements. i.e., we can place
an if statement inside another if statement.

Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here

Flowchart of Python Nested if Statement

Flowchart of Python Nested if statement

Example of Python Nested if statement

In this example, we are showing nested if conditions in the code, All the If
conditions will be executed one by one.

Python3
# python program to illustrate nested If
statement

i = 10

if (i == 10):

# First if statement

if (i < 15):

print("i is smaller than 15")

# Nested - if statement
# Will only be executed if statement above

# it is true

if (i < 12):

print("i is smaller than 12 too")

else:

print("i is greater than 15")

Output:
i is smaller than 15
i is smaller than 12 too

Python if-elif-else Ladder


Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of
the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.

Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement

Flowchart of Python if-elif-else ladder

Flowchart of if-elif-else ladder

Example of Python if-elif-else ladder


In the example, we are showing single if condition and multiple elif
conditions, and single else condition.

Python3

# Python program to illustrate if-elif-else


ladder

#!/usr/bin/python

i = 20

if (i == 10):

print("i is 10")

elif (i == 15):

print("i is 15")
elif (i == 20):

print("i is 20")

else:

print("i is not present")

Output:
i is 20

Short Hand if statement


Whenever there is only a single statement to be executed inside the if block
then shorthand if can be used. The statement can be put on the same line as
the if statement.

Syntax:
if condition: statement

Example of Python if shorthand

In the given example, we have a condition that if the number is less than 15,
then further code will be executed.

Python3
# Python program to illustrate short hand if

i = 10

if i < 15: print("i is less than 15")

Output:
i is less than 15

Short Hand if-else statement


This can be used to write the if-else statements in a single line where only
one statement is needed in both the if and else blocks.

Syntax:
statement_when_True if condition else statement_when_False

Example of Python if else shorthand

In the given example, we are printing True if the number is 15 else it will
print False.

Python3
# Python program to illustrate short hand
if-else

i = 10

print(True) if i < 15 else print(False)

Output:
True

Lists/Nested Lists:
Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java). In simple language, a list is a
collection of things, enclosed in [ ] and separated by commas.

The list is a sequence data type which is used to store the collection of data.
Tuples and String are other types of sequence data types.

Example of list in Python


Here we are creating Python List using [].

Python3
Var = ["Geeks", "for", "Geeks"]

print(Var)

Output:
["Geeks", "for", "Geeks"]

Lists are the simplest containers that are an integral part of the Python
language. Lists need not be homogeneous always which makes it the most
powerful tool in Python. A single list may contain DataTypes like Integers,
Strings, as well as Objects. Lists are mutable, and hence, they can be altered
even after their creation.

Creating a List in Python


Lists in Python can be created by just placing the sequence inside the square
brackets[]. Unlike Sets, a list doesn’t need a built-in function for its creation
of a list.

Note: Unlike Sets, the list may contain mutable elements.

Example 1: Creating a list in Python

Python3
# Python program to demonstrate

# Creation of List

# Creating a List

List = []

print("Blank List: ")

print(List)

# Creating a List of numbers

List = [10, 20, 14]


print("\nList of numbers: ")

print(List)

# Creating a List of strings and accessing

# using index

List = ["Geeks", "For", "Geeks"]

print("\nList Items: ")

print(List[0])

print(List[2])

Output
Blank List:
[]

List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks

Complexities for Creating Lists


Time Complexity: O(1)

Space Complexity: O(n)

Example 2: Creating a list with multiple distinct or duplicate elements

A list may contain duplicate values with their distinct positions and hence,
multiple distinct or duplicate values can be passed as a sequence at the time
of list creation.

Python3

# Creating a List with

# the use of Numbers

# (Having duplicate values)

List = [1, 2, 4, 4, 3, 3, 3, 6, 5]

print("\nList with the use of Numbers: ")


print(List)

# Creating a List with

# mixed type of values

# (Having numbers and strings)

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

print("\nList with the use of Mixed Values:


")

print(List)

Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]

List with the use of Mixed Values:


[1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

Accessing elements from the List


In order to access the list items refer to the index number. Use the index
operator [ ] to access an item in a list. The index must be an integer. Nested
lists are accessed using nested indexing.

Example 1: Accessing elements from list

Python3

# 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 a element from the list")

print(List[0])

print(List[2])

Output
Accessing a element from the list
Geeks
Geeks

Example 2: Accessing elements from a multi-dimensional list

Python3

# Creating a Multi-Dimensional List

# (By Nesting a list inside a List)

List = [['Geeks', 'For'], ['Geeks']]


# accessing an element from the

# Multi-Dimensional List using

# index number

print("Accessing a element from a Multi-Dimensional


list")

print(List[0][1])

print(List[1][0])

Output
Accessing a element from a Multi-Dimensional list
For
Geeks

Negative indexing

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

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

# accessing an 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 using negative indexing
Geeks
For

Complexities for Accessing elements in a Lists:


Time Complexity: O(1)

Space Complexity: O(1)

Getting the size of Python list


Python len() is used to get the length of the list.

Python3

# Creating a List

List1 = []

print(len(List1))
# Creating a List of numbers

List2 = [10, 20, 14]

print(len(List2))

Output
0
3

Taking Input of a Python List


We can take the input of a list of elements as string, integer, float, etc. But
the default one is a string.

Example 1:

Python3
# Python program to take space

# separated input as a string

# split and store it to a list

# and print the string list

# input the list as string

string = input("Enter elements (Space-Separated):


")

# split the strings and store it to a list

lst = string.split()
print('The list is:', lst) # printing the list

Output:
Enter elements: GEEKS FOR GEEKS
The list is: ['GEEKS', 'FOR', 'GEEKS']

Example 2:

Python

# input size of the list

n = int(input("Enter the size of list : "))

# store integers in a list using map,

# split and strip functions

lst = list(map(int, input("Enter the integer\

elements:").strip().split()))[:n]
# printing the list

print('The list is:', lst)

Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]

To know more see this.

Adding Elements to a Python List

Method 1: Using append() method

Elements can be added to the List by using the built-in append() function.
Only one element at a time can be added to the list by using the append()
method, for the addition of multiple elements with the append() method,
loops are used. Tuples can also be added to the list with the use of the
append method because tuples are immutable. Unlike Sets, Lists can also be
added to the existing list with the use of the append() method.

Python3
# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = []

print("Initial blank List: ")

print(List)

# Addition of Elements

# in the List
List.append(1)

List.append(2)

List.append(4)

print("\nList after Addition of Three elements: ")

print(List)

# Adding elements to the List

# using Iterator

for i in range(1, 4):

List.append(i)

print("\nList after Addition of elements from 1-3:


")
print(List)

# Adding Tuples to the List

List.append((5, 6))

print("\nList after Addition of a Tuple: ")

print(List)

# Addition of List to a List

List2 = ['For', 'Geeks']

List.append(List2)

print("\nList after Addition of a List: ")


print(List)

Output
Initial blank List:
[]

List after Addition of Three elements:


[1, 2, 4]

List after Addition of elements from 1-3:


[1, 2, 4, 1, 2, 3]

List after Addition of a Tuple:


[1, 2, 4, 1, 2, 3, (5, 6)]

List after Addition of a List:


[1, 2, 4, 1, 2, 3, (5, 6), ['For', 'Geeks']]

Complexities for Adding elements in a Lists(append() method):


Time Complexity: O(1)

Space Complexity: O(1)

Method 2: Using insert() method

append() method only works for the addition of elements at the end of the
List, for the addition of elements at the desired position, insert() method is
used. Unlike append() which takes only one argument, the insert() method
requires two arguments(position, value).

Python3
# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = [1,2,3,4]

print("Initial List: ")

print(List)

# Addition of Element at

# specific Position
# (using Insert Method)

List.insert(3, 12)

List.insert(0, 'Geeks')

print("\nList after performing Insert Operation:


")

print(List)

Output
Initial List:
[1, 2, 3, 4]

List after performing Insert Operation:


['Geeks', 1, 2, 3, 12, 4]

Complexities for Adding elements in a Lists(insert() method):


Time Complexity: O(n)

Space Complexity: O(1)

Method 3: Using extend() method

Other than append() and insert() methods, there’s one more method for the
Addition of elements, extend(), this method is used to add multiple elements
at the same time at the end of the list.
Note: append() and extend() methods can only add elements at the end.

Python3

# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = [1, 2, 3, 4]

print("Initial List: ")

print(List)

# Addition of multiple elements


# to the List at the end

# (using Extend Method)

List.extend([8, 'Geeks', 'Always'])

print("\nList after performing Extend Operation:


")

print(List)

Output
Initial List:
[1, 2, 3, 4]

List after performing Extend Operation:


[1, 2, 3, 4, 8, 'Geeks', 'Always']

Complexities for Adding elements in a Lists(extend() method):


Time Complexity: O(n)

Space Complexity: O(1)

Reversing a List

Method 1: A list can be reversed by using the reverse() method in


Python.

Python3
# Reversing a list

mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']

mylist.reverse()

print(mylist)

Output
['Python', 'Geek', 5, 4, 3, 2, 1]

Method 2: Using the reversed() function:

The reversed() function returns a reverse iterator, which can be converted to


a list using the list() function.

Python3

my_list = [1, 2, 3, 4, 5]

reversed_list = list(reversed(my_list))
print(reversed_list)

Output
[5, 4, 3, 2, 1]

Removing Elements from the List

Method 1: Using remove() method

Elements can be removed from the List by using the built-in remove()
function but an Error arises if the element doesn’t exist in the list. Remove()
method only removes one element at a time, to remove a range of elements,
the iterator is used. The remove() method removes the specified item.

Note: Remove method in List will only remove the first occurrence of the
searched element.

Example 1:

Python3
# Python program to demonstrate

# Removal of elements in a List

# Creating a List

List = [1, 2, 3, 4, 5, 6,

7, 8, 9, 10, 11, 12]

print("Initial List: ")

print(List)

# Removing elements from List


# using Remove() method

List.remove(5)

List.remove(6)

print("\nList after Removal of two elements:


")

print(List)

Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

List after Removal of two elements:


[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]

Example 2:

Python3

# Creating a List
List = [1, 2, 3, 4, 5, 6,

7, 8, 9, 10, 11, 12]

# Removing elements from List

# using iterator method

for i in range(1, 5):

List.remove(i)

print("\nList after Removing a range of elements:


")

print(List)

Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]

Complexities for Deleting elements in a Lists(remove() method):


Time Complexity: O(n)

Space Complexity: O(1)


Method 2: Using pop() method

pop() function can also be used to remove and return an element from the
list, but by default it removes only the last element of the list, to remove an
element from a specific position of the List, the index of the element is
passed as an argument to the pop() method.

Python3

List = [1, 2, 3, 4, 5]

# Removing element from the

# Set using the pop() method

List.pop()

print("\nList after popping an element: ")

print(List)
# Removing element at a

# specific location from the

# Set using the pop() method

List.pop(2)

print("\nList after popping a specific element:


")

print(List)

Output
List after popping an element:
[1, 2, 3, 4]

List after popping a specific element:


[1, 2, 4]

Complexities for Deleting elements in a Lists(pop() method):


Time Complexity: O(1)/O(n) (O(1) for removing the last element, O(n) for
removing the first and middle elements)

Space Complexity: O(1)


Slicing of a List
We can get substrings and sublists using a slice. In Python List, there are
multiple ways to print the whole list with all the elements, but to print a
specific range of elements from the list, we use the Slice operation.

Slice operation is performed on Lists with the use of a colon(:).

To print elements from beginning to a range use:

[: Index]

To print elements from end-use:

[:-Index]

To print elements from a specific Index till the end use

[Index:]

To print the whole list in reverse order, use

[::-1]

Note – To print elements of List from rear-end, use Negative Indexes.


UNDERSTANDING SLICING OF LISTS:

● pr[0] accesses the first item, 2.

● pr[-4] accesses the fourth item from the end, 5.

● pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.

● pr[:4] accesses [2, 3, 5, 7], a list of items from first to fourth.

● pr[2:4] accesses [5, 7], a list of items from third to fifth.

● pr[1::2] accesses [3, 7, 13], alternate items, starting from the second

item.

Python3
# Python program to demonstrate

# Removal of elements in a List

# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F',

'O', 'R', 'G', 'E', 'E', 'K', 'S']

print("Initial List: ")

print(List)

# Print elements of a range


# using Slice operation

Sliced_List = List[3:8]

print("\nSlicing elements in a range 3-8: ")

print(Sliced_List)

# Print elements from a

# pre-defined point to end

Sliced_List = List[5:]

print("\nElements sliced from 5th "

"element till the end: ")

print(Sliced_List)
# Printing elements from

# beginning till end

Sliced_List = List[:]

print("\nPrinting all elements using slice operation:


")

print(Sliced_List)

Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K',
'S']

Slicing elements in a range 3-8:


['K', 'S', 'F', 'O', 'R']

Elements sliced from 5th element till the end:


['F', 'O', 'R', 'G', 'E', 'E', 'K', 'S']

Printing all elements using slice operation:


['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K',
'S']
Negative index List slicing

Python3

# Creating a List

List = ['G', 'E', 'E', 'K', 'S', 'F',

'O', 'R', 'G', 'E', 'E', 'K', 'S']

print("Initial List: ")

print(List)

# Print elements from beginning

# to a pre-defined point using Slice

Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last:
")

print(Sliced_List)

# Print elements of a range

# using negative index List slicing

Sliced_List = List[-6:-1]

print("\nElements sliced from index -6 to -1")

print(Sliced_List)

# Printing elements in reverse


# using Slice operation

Sliced_List = List[::-1]

print("\nPrinting List in reverse: ")

print(Sliced_List)

Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K',
'S']

Elements sliced till 6th element from last:


['G', 'E', 'E', 'K', 'S', 'F', 'O']

Elements sliced from index -6 to -1


['R', 'G', 'E', 'E', 'K']

Printing List in reverse:


['S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E',
'G']

List Comprehension
Python List comprehensions are used for creating new lists from other
iterables like tuples, strings, arrays, lists, etc. A list comprehension consists
of brackets containing the expression, which is executed for each element
along with the for loop to iterate over each element.

Syntax:
newList = [ expression(element) for element in oldList if condition ]

Example:

Python3

# Python program to demonstrate list

# comprehension in Python

# below list contains square of all

# odd numbers from range 1 to 10

odd_square = [x ** 2 for x in range(1, 11) if x % 2 ==


1]

print(odd_square)

Output
[1, 9, 25, 49, 81]

For better understanding, the above code is similar to as follows:


Python3

# for understanding, above generation is same


as,

odd_square = []

for x in range(1, 11):

if x % 2 == 1:

odd_square.append(x**2)

print(odd_square)

Output
[1, 9, 25, 49, 81]

Refer to the below articles to get detailed information about List


Comprehension.
● Python List Comprehension and Slicing

● Nested List Comprehensions in Python

● List comprehension and ord() in Python

Basic Example on Python List


● Python program to interchange first and last elements in a list

● Python program to swap two elements in a list

● Python – Swap elements in String list

● Python | Ways to find length of list

● Maximum of two numbers in Python

● Minimum of two numbers in Python

To Practice the basic list operation, please read this article – Python List of
program

List Methods

Function Description

Append(
Add an element to the end of the list
)
Extend() Add all elements of a list to another list

Insert() Insert an item at the defined index

Remove(
Removes an item from the list
)

Clear() Removes all items from the list

Index() Returns the index of the first matched item

Returns the count of the number of items passed as an


Count()
argument

Sort() Sort items in a list in ascending order


Reverse(
Reverse the order of items in the list
)

copy() Returns a copy of the list

Removes and returns the item at the specified index. If no


pop()
index is provided, it removes and returns the last item.

To know more refer to this article – Python List methods

The operations mentioned above modify the list Itself.

Built-in functions with List

Function Description

apply a particular function passed in its argument to all of


reduce() the list elements stores the intermediate result and only
returns the final summation value
sum() Sums up the numbers in the list

Returns an integer representing the Unicode code point of


ord()
the given Unicode character

This function returns 1 if the first list is “greater” than the


cmp()
second list

max() return maximum element of a given list

min() return minimum element of a given list

all() Returns true if all element is true or if the list is empty

return true if any element of the list is true. if the list is


any()
empty, return false
len() Returns length of the list or size of the list

enumerate() Returns enumerate object of the list

apply a particular function passed in its argument to all of


accumulate(
the list elements returns a list containing the intermediate
)
results

filter() tests if each element of a list is true or not

returns a list of the results after applying the given


map()
function to each item of a given iterable

This function can have any number of arguments but only


lambda()
one expression, which is evaluated and returned.

Tuple:
Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple
can be of any type, and they are indexed by integers.
Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is
more common to define a tuple by closing the sequence of values in parentheses. This helps in
understanding the Python tuples more easily.

Creating a Tuple
In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or
without the use of parentheses for grouping the data sequence.

Note: Creation of Python tuple without the use of parentheses is known as Tuple Packing.

Python program to demonstrate the addition of elements in a Tuple.


Python3

# Creating an empty Tuple

Tuple1 = ()

print("Initial empty Tuple: ")

print(Tuple1)

# Creating a Tuple

# with the use of string


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)

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

Creating a Tuple with Mixed Datatypes.


Tuples can contain any number of elements and of any datatype (like strings, integers, list,
etc.). 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.

Python3
# Creating a Tuple

# with Mixed Datatype

Tuple1 = (5, 'Welcome', 7, 'Geeks')

print("\nTuple with Mixed Datatypes: ")

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)

# Creating a Tuple

# with repetition

Tuple1 = ('Geeks',) * 3

print("\nTuple with repetition: ")

print(Tuple1)

# Creating a Tuple
# with the use of loop

Tuple1 = ('Geeks')

n=5

print("\nTuple with a loop")

for i in range(int(n)):

Tuple1 = (Tuple1,)

print(Tuple1)

Output:

Tuple with Mixed Datatypes:


(5, 'Welcome', 7, 'Geeks')

Tuple with nested tuples:


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

Tuple with repetition:


('Geeks', 'Geeks', 'Geeks')

Tuple with a loop


('Geeks',)
(('Geeks',),)
((('Geeks',),),)
(((('Geeks',),),),)
((((('Geeks',),),),),)

Complexities for creating tuples:

Time complexity: O(1)

Auxiliary Space : O(n)

Accessing of Tuples
Tuples are immutable, and usually, they contain a sequence of heterogeneous elements that
are accessed via unpacking or indexing (or even by attribute in the case of named tuples). Lists
are mutable, and their elements are usually homogeneous and are accessed by iterating over
the list.

Note: In unpacking of tuple number of variables on the left-hand side should be equal to a
number of values in given tuple a.

Python3

# Accessing Tuple

# with Indexing

Tuple1 = tuple("Geeks")

print("\nFirst element of Tuple: ")

print(Tuple1[0])
# Tuple unpacking

Tuple1 = ("Geeks", "For", "Geeks")

# This line unpack

# values of Tuple1

a, b, c = Tuple1

print("\nValues after unpacking: ")

print(a)

print(b)

print(c)

Output:
First element of Tuple:
G

Values after unpacking:


Geeks
For
Geeks

Complexities for accessing elements in tuples:

Time complexity: O(1)

Space complexity: O(1)

Concatenation of Tuples
Concatenation of tuple is the process of joining two or more Tuples. Concatenation is done by
the use of ‘+’ operator. Concatenation of tuples is done always from the end of the original tuple.
Other arithmetic operations do not apply on Tuples.

Note- Only the same datatypes can be combined with concatenation, an error arises if a list and
a tuple are combined.

Python3
# Concatenation of tuples

Tuple1 = (0, 1, 2, 3)

Tuple2 = ('Geeks', 'For', 'Geeks')

Tuple3 = Tuple1 + Tuple2

# Printing first Tuple

print("Tuple 1: ")

print(Tuple1)
# Printing Second Tuple

print("\nTuple2: ")

print(Tuple2)

# Printing Final Tuple

print("\nTuples after Concatenation: ")

print(Tuple3)

Output:

Tuple 1:
(0, 1, 2, 3)

Tuple2:
('Geeks', 'For', 'Geeks')

Tuples after Concatenation:


(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

Time Complexity: O(1)

Auxiliary Space: O(1)

Slicing of Tuple
Slicing of a Tuple is done to fetch a specific range or slice of sub-elements from a Tuple. Slicing
can also be done to lists and arrays. Indexing in a list results to fetching a single element
whereas Slicing allows to fetch a set of elements.

Note- Negative Increment values can also be used to reverse the sequence of Tuples.

Python3

# Slicing of a Tuple

# Slicing of a Tuple

# with Numbers

Tuple1 = tuple('GEEKSFORGEEKS')
# Removing First element

print("Removal of First Element: ")

print(Tuple1[1:])

# Reversing the Tuple

print("\nTuple after sequence of Element is reversed: ")

print(Tuple1[::-1])

# Printing elements of a Range

print("\nPrinting elements between Range 4-9: ")

print(Tuple1[4:9])

Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')

Tuple after sequence of Element is reversed:


('S', 'K', 'E', 'E', 'G', 'R', 'O', 'F', 'S', 'K', 'E', 'E', 'G')

Printing elements between Range 4-9:


('S', 'F', 'O', 'R', 'G')

Complexities for traversal/searching elements in tuples:

Time complexity: O(1)

Space complexity: O(1)

Deleting a Tuple
Tuples are immutable and hence they do not allow deletion of a part of it. The entire tuple gets
deleted by the use of del() method.

Note- Printing of Tuple after deletion results in an Error.

Python

# Deleting a Tuple

Tuple1 = (0, 1, 2, 3, 4)

del Tuple1
print(Tuple1)

Traceback (most recent call last):


File “/home/efa50fd0709dec08434191f32275928a.py”, line 7, in
print(Tuple1)
NameError: name ‘Tuple1’ is not defined

Built-In Methods

Built-in-Method Description

Find in the tuple and returns the index of the given value where it’s
index( )
available

count( ) Returns the frequency of occurrence of a specified value

Built-In Functions

Built-in Function Description

all() Returns true if all element are true or if tuple is empty


return true if any element of the tuple is true. if tuple is empty,
any()
return false

len() Returns length of the tuple or size of the tuple

enumerate() Returns enumerate object of tuple

max() return maximum element of given tuple

min() return minimum element of given tuple

sum() Sums up the numbers in the tuple

sorted() input elements in the tuple and return a new sorted list

tuple() Convert an iterable to a tuple.


Tuples VS Lists:

Similarities Differences

Functions that can be used


Methods that cannot be used for tuples:
for both lists and tuples:

append(), insert(), remove(), pop(), clear(), sort(),


len(), max(), min(), sum(),
reverse()
any(), all(), sorted()

Methods that can be used


for both lists and tuples: we generally use ‘tuples’ for heterogeneous (different)
data types and ‘lists’ for homogeneous (similar) data
types.
count(), Index()

Tuples can be stored in lists. Iterating through a ‘tuple’ is faster than in a ‘list’.

Lists can be stored in tuples. ‘Lists’ are mutable whereas ‘tuples’ are immutable.
Both ‘tuples’ and ‘lists’ can Tuples that contain immutable elements can be used
be nested. as a key for a dictionary.

You might also like