Python SIM
Python SIM
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.
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.
= 2610
Computer memory is measured in terms of how many bits it can store. Here is a chart for
memory capacity conversion.
Decimal equivalent of any octal number is sum of product of each digit with its positional value.
= 448 + 16 + 6
= 47010
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
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
# 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
print(v)
print(w)
Output
n
a
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
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.
Set literal
Set is the collection of the unordered data set. It is enclosed by the {} and each element is
separated by the comma(,).
print(vowels)
print(fruits)
Output
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.
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
125
678
# 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
Python3
# display
print( Number)
Output:
100
Python3
# display
print("Before declare: ", Number)
Python3
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
Python3
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks
Python3
a = 10
a = "GeeksforGeeks"
print(a)
Output:
GeeksforGeeks
Python3
a = 10
b = 20
print(a+b)
a = "Geeksfor"
b = "Geeks"
print(a+b)
Output
30
GeeksforGeeks
Python3
a = 10
b = "Geeks"
print(a+b)
Output :
Python3
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
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
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:
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 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'>
x=5
Object References
Another variable is y to the variable x.
y=x
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
class CSStudent:
# Class Variable
stream = 'cse'
# Instance Variable
self.roll = roll
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)
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
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:
● 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 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
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
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:
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
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.
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:
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.
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
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:
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
Elements of set:
Geeks For
True
Note – To know more about sets, refer to Python Sets.
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:
{}
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'.
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.
1. The if statement
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 the condition present in the if statement is false. So, the block below the
if statement is executed.
Python3
i = 10
if (i > 15):
Output:
I am Not in if
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
#!/usr/bin/python
i = 20
if (i < 15):
print("i'm in if Block")
else:
Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block
Python3
# Explicit function
def digitSum(n):
dsum = 0
dsum += int(ele)
return dsum
# Initializing list
print(newList)
Output :
[16, 3, 18, 18]
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
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):
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
else:
Output:
i is smaller than 15
i is smaller than 12 too
Syntax:
if (condition):
statement
elif (condition):
statement
.
.
else:
statement
Python3
#!/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:
Output:
i is 20
Syntax:
if condition: statement
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
Output:
i is less than 15
Syntax:
statement_when_True if condition else statement_when_False
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
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.
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.
Python3
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print(List)
print(List)
# using index
print(List[0])
print(List[2])
Output
Blank List:
[]
List of numbers:
[10, 20, 14]
List Items:
Geeks
Geeks
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
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print(List)
Output
List with the use of Numbers:
[1, 2, 4, 4, 3, 3, 3, 6, 5]
Python3
print(List[0])
print(List[2])
Output
Accessing a element from the list
Geeks
Geeks
Python3
# index number
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
# negative indexing
print(List[-1])
# print the third last element of list
print(List[-3])
Output
Accessing element using negative indexing
Geeks
For
Python3
# Creating a List
List1 = []
print(len(List1))
# Creating a List of numbers
print(len(List2))
Output
0
3
Example 1:
Python3
# Python program to take space
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
elements:").strip().split()))[:n]
# printing the list
Output:
Enter the size of list : 4
Enter the integer elements: 6 3 9 10
The list is: [6, 3, 9, 10]
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
# Creating a List
List = []
print(List)
# Addition of Elements
# in the List
List.append(1)
List.append(2)
List.append(4)
print(List)
# using Iterator
List.append(i)
List.append((5, 6))
print(List)
List.append(List2)
Output
Initial blank List:
[]
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
# Creating a List
List = [1,2,3,4]
print(List)
# Addition of Element at
# specific Position
# (using Insert Method)
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
Output
Initial List:
[1, 2, 3, 4]
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
# Creating a List
List = [1, 2, 3, 4]
print(List)
print(List)
Output
Initial List:
[1, 2, 3, 4]
Reversing a List
Python3
# Reversing a list
mylist.reverse()
print(mylist)
Output
['Python', 'Geek', 5, 4, 3, 2, 1]
Python3
my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)
Output
[5, 4, 3, 2, 1]
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
# Creating a List
List = [1, 2, 3, 4, 5, 6,
print(List)
List.remove(5)
List.remove(6)
print(List)
Output
Initial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Example 2:
Python3
# Creating a List
List = [1, 2, 3, 4, 5, 6,
List.remove(i)
print(List)
Output
List after Removing a range of elements:
[5, 6, 7, 8, 9, 10, 11, 12]
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]
List.pop()
print(List)
# Removing element at a
List.pop(2)
print(List)
Output
List after popping an element:
[1, 2, 3, 4]
[: Index]
[:-Index]
[Index:]
[::-1]
● pr[2:] accesses [5, 7, 11, 13], a list of items from third to last.
● pr[1::2] accesses [3, 7, 13], alternate items, starting from the second
item.
Python3
# Python program to demonstrate
# Creating a List
print(List)
Sliced_List = List[3:8]
print(Sliced_List)
Sliced_List = List[5:]
print(Sliced_List)
# Printing elements from
Sliced_List = List[:]
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K',
'S']
Python3
# Creating a List
print(List)
Sliced_List = List[:-6]
print("\nElements sliced till 6th element from last:
")
print(Sliced_List)
Sliced_List = List[-6:-1]
print(Sliced_List)
Sliced_List = List[::-1]
print(Sliced_List)
Output
Initial List:
['G', 'E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K',
'S']
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
# comprehension in Python
print(odd_square)
Output
[1, 9, 25, 49, 81]
odd_square = []
if x % 2 == 1:
odd_square.append(x**2)
print(odd_square)
Output
[1, 9, 25, 49, 81]
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
Remove(
Removes an item from the list
)
Function Description
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.
Tuple1 = ()
print(Tuple1)
# Creating a Tuple
print(Tuple1)
list1 = [1, 2, 4, 5, 6]
print(tuple(list1))
# Creating a Tuple
# with the use of built-in function
Tuple1 = tuple('Geeks')
print(Tuple1)
Output:
Python3
# Creating a Tuple
print(Tuple1)
# Creating a Tuple
Tuple1 = (0, 1, 2, 3)
print(Tuple3)
# Creating a Tuple
# with repetition
Tuple1 = ('Geeks',) * 3
print(Tuple1)
# Creating a Tuple
# with the use of loop
Tuple1 = ('Geeks')
n=5
for i in range(int(n)):
Tuple1 = (Tuple1,)
print(Tuple1)
Output:
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(Tuple1[0])
# Tuple unpacking
# values of Tuple1
a, b, c = Tuple1
print(a)
print(b)
print(c)
Output:
First element of Tuple:
G
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)
print("Tuple 1: ")
print(Tuple1)
# Printing Second Tuple
print("\nTuple2: ")
print(Tuple2)
print(Tuple3)
Output:
Tuple 1:
(0, 1, 2, 3)
Tuple2:
('Geeks', 'For', 'Geeks')
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(Tuple1[1:])
print(Tuple1[::-1])
print(Tuple1[4:9])
Output:
Removal of First Element:
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
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.
Python
# Deleting a Tuple
Tuple1 = (0, 1, 2, 3, 4)
del Tuple1
print(Tuple1)
Built-In Methods
Built-in-Method Description
Find in the tuple and returns the index of the given value where it’s
index( )
available
Built-In Functions
sorted() input elements in the tuple and return a new sorted list
Similarities Differences
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.