Harwinder Singh Sohal
Python(INT-108)
Python 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.
# DataType Output: str
x = "Hello World"
# DataType Output: int
Harwinder Singh Sohal
Python(INT-108)
x = 50
# DataType Output: float
x = 60.5
# DataType Output: complex
x = 3j
# DataType Output: list
x = ["geeks", "for", "geeks"]
# DataType Output: tuple
x = ("geeks", "for", "geeks")
# DataType Output: range
x = range(10)
# DataType Output: dict
x = {"name": "Suraj", "age": 24}
# DataType Output: set
x = {"geeks", "for", "geeks"}
# DataType Output: frozenset
x = frozenset({"geeks", "for", "geeks"})
# DataType Output: bool
x = True
# DataType Output: bytes
Harwinder Singh Sohal
Python(INT-108)
x = b"Geeks"
# DataType Output: bytearray
x = bytearray(4)
# DataType Output: memoryview
x = memoryview(bytes(6))
# DataType Output: NoneType
x = None
Numeric Data Type 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.
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
Harwinder Singh Sohal
Python(INT-108)
print("\nType of c: ", type(c))
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.
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
Harwinder Singh Sohal
Python(INT-108)
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
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.
Python3
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
Harwinder Singh Sohal
Python(INT-108)
print("\nLast character of String is: ")
print(String1[-1])
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
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Creating a List
List = []
print("Initial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List
# (By Nesting a list inside a List)
Harwinder Singh Sohal
Python(INT-108)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
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.
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 element from the list")
print(List[0])
print(List[2])
# accessing a element using
# negative indexing
print("Accessing element using negative indexing")
# print the last element of list
print(List[-1])
Harwinder Singh Sohal
Python(INT-108)
# print the third last element of list
print(List[-3])
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, 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.
Python3
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print(Tuple1)
# Creating a Tuple with
# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)
# Creating a Tuple with
# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))
Harwinder Singh Sohal
Python(INT-108)
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
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.
# Python program to
# demonstrate accessing tuple
tuple1 = tuple([1, 2, 3, 4, 5])
# Accessing element using indexing
print("First element of tuple")
print(tuple1[0])
# Accessing element from last
# negative indexing
Harwinder Singh Sohal
Python(INT-108)
print("\nLast element of tuple")
print(tuple1[-1])
print("\nThird last element of tuple")
print(tuple1[-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.
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
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.
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
Harwinder Singh Sohal
Python(INT-108)
set1 = set()
print("Initial blank Set: ")
print(set1)
# Creating a Set with
# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)
# Creating a Set with
# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)
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.
# Python program to demonstrate
# Accessing of elements in a set
# Creating a set
Harwinder Singh Sohal
Python(INT-108)
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
# Accessing element using
# for loop
print("\nElements of set: ")
for i in set1:
print(i, end=" ")
# Checking the element
# using in keyword
print("Geeks" in set1)
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, 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.
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
Harwinder Singh Sohal
Python(INT-108)
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
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.
# Python program to demonstrate
# accessing a element from a Dictionary
Harwinder Singh Sohal
Python(INT-108)
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# accessing a element using key
print("Accessing a element using key:")
print(Dict['name'])
# accessing a element using get()
# method
print("Accessing a element using get:")
print(Dict.get(3))
Python | Set 3 (Strings, Lists, Tuples, Iterations)
Strings in Python:
A string is a sequence of characters that can be a combination of letters, numbers, and special
characters. It can be declared in python by using single quotes, double quotes, or even triple
quotes. These quotes are not a part of a string, they define only starting and ending of the
string. Strings are immutable, i.e., they cannot be changed. Each element of the string can
be accessed using indexing or slicing operations.
# Assigning string to a variable
a = 'This is a string'
print (a)
b = "This is a string"
print (b)
c= '''This is a string'''
print (c)
Lists in Python:
Lists are one of the most powerful data structures in python. Lists are sequenced data
types. In Python, an empty list is created using list() function. They are just like the arrays
declared in other languages. But the most powerful thing is that list need not be always
homogeneous. A single list can contain strings, integers, as well as other objects. Lists can
also be used for implementing stacks and queues. Lists are mutable, i.e., they can be altered
once declared. The elements of list can be accessed using indexing and slicing operations.
Harwinder Singh Sohal
Python(INT-108)
# Declaring a list
L = [1, "a" , "string" , 1+2]
print L
#Adding an element in the list
L.append(6)
print L
#Deleting last element from a list
L.pop()
print (L)
#Displaying Second element of the list
print (L[1])
Tuples in Python: A tuple is a sequence of immutable Python objects. Tuples are just
like lists with the exception that tuples cannot be changed once declared. Tuples are
usually faster than lists.
tup = (1, "a", "string", 1+2)
print(tup)
print(tup[1])
Iterations in Python: Iterations or looping can be performed in python by ‘for’ and ‘while’
loops. Apart from iterating upon a particular condition, we can also iterate on strings, lists,
and tuples.
Example 1: Iteration by while loop for a condition
i=1
while (i < 10):
print(i)
i += 1
Example 2: Iteration by for loop on the string
s = "Hello World"
for i in s:
print(i)
Example 3: Iteration by for loop on list
L = [1, 4, 5, 7, 8, 9]
for i in L:
print(i)
Example 4: Iteration by for loop for range
for i in range(0, 10):
print(i)
Python String
A string is a data structure in Python that represents a sequence of characters. It is an
immutable data type, meaning that once you have created a string, you cannot change
Harwinder Singh Sohal
Python(INT-108)
it. Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data that
can be represented as text.
Example:
Python does not have a character data type, a single character is simply a string with a
length of 1. Square brackets can be used to access elements of the string.
print("A Computer Science portal for geeks")
Creating a String in Python
Strings in Python can be created using single quotes or double quotes or even triple
quotes.
Python3
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
# Creating String with triple
# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Accessing characters in Python String
In Python, individual characters of a String can be accessed by using the method of
Indexing. Indexing allows negative address references to access characters from the back of
the String, e.g. -1 refers to the last character, -2 refers to the second last character, and so
on.
Harwinder Singh Sohal
Python(INT-108)
While accessing an index out of the range will cause an IndexError. Only Integers are
allowed to be passed as an index, float or other types that will cause a TypeError
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])
Reversing a Python String
With Accessing Characters from a string, we can also reverse them. We can Reverse a
string by writing [::-1] and the string will be reversed
#Program to reverse a string
gfg = "geeksforgeeks"
print(gfg[::-1])
# Program to reverse a string
gfg = "geeksforgeeks"
# Reverse the string using reversed and join function
gfg = "".join(reversed(gfg))
print(gfg)
Harwinder Singh Sohal
Python(INT-108)
String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a
String is done by using a Slicing operator (colon).
# Python Program to
# demonstrate String slicing
# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between
# 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])
Deleting/Updating from a String
In Python, the Updation or deletion of characters from a String is not allowed. This will
cause an error because item assignment or item deletion from a String is not supported.
Although deletion of the entire String is possible with the use of a built-in del keyword.
This is because Strings are immutable, hence elements of a String cannot be changed once
it has been assigned. Only new strings can be reassigned to the same name.
Updation of a character:
# Python Program to Update
# character of a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a character of the String
## As python strings are immutable, they don't support item updation directly
### there are following two ways
Harwinder Singh Sohal
Python(INT-108)
#1
list1 = list(String1)
list1[2] = 'p'
String2 = ''.join(list1)
print("\nUpdating character at 2nd Index: ")
print(String2)
#2
String3 = String1[0:2] + 'p' + String1[3:]
print(String3)
Updating Entire String:
# Python Program to Update
# entire String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)
Deletion of a character:
# Python Program to Delete
# characters from a String
String1 = "Hello, I'm a Geek"
Harwinder Singh Sohal
Python(INT-108)
print("Initial String: ")
print(String1)
# Deleting a character
# of the String
String2 = String1[0:2] + String1[3:]
print("\nDeleting character at 2nd Index: ")
print(String2)
eleting Entire String:
Deletion of the entire string is possible with the use of del keyword. Further, if we try to
print the string, this will produce an error because String is deleted and is unavailable to be
printed.
# Python Program to Delete
# entire String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Deleting a String
# with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
scape Sequencing in Python
While printing Strings with single and double quotes in it causes SyntaxError because
String already contains Single and Double Quotes and hence cannot be printed with the use
of either of these. Hence, to print such a String either Triple Quotes are used or Escape
sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes
are used to represent a string, then all the single quotes present in the string must be
escaped and same is done for Double Quotes.
Harwinder Singh Sohal
Python(INT-108)
# Python Program for
# Escape Sequencing
# of String
# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)
# Escaping Single Quote
String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)
# Escaping Double Quotes
String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)
# Printing Paths with the
# use of Escape Sequences
String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)
# Printing Paths with the
# use of Tab
String1 = "Hi\tGeeks"
print("\nTab: ")
print(String1)
Harwinder Singh Sohal
Python(INT-108)
# Printing Paths with the
# use of New Line
String1 = "Python\nGeeks"
print("\nNew Line: ")
print(String1)
To ignore the escape sequences in a String, r or R is used, this implies that the string is a
raw string and escape sequences inside it are to be i
# Printing hello in octal
String1 = "\110\145\154\154\157"
print("\nPrinting in Octal with the use of Escape Sequences: ")
print(String1)
# Using raw String to
# ignore Escape Sequences
String1 = r"This is \110\145\154\154\157"
print("\nPrinting Raw String in Octal Format: ")
print(String1)
# Printing Geeks in HEX
String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)
# Using raw String to
# ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)
Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very
versatile and powerful tool for formatting Strings. Format method in String contains curly
braces {} as placeholders which can hold arguments according to position or keyword to
specify the order.
Python3
# Python Program for
# Formatting of Strings
# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
Harwinder Singh Sohal
Python(INT-108)
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)
# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)
Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the
exponent form with the use of format specifiers.
# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)
# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)
# Rounding off Integers
String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)
A string can be left() or center(^) justified with the use of format specifiers, separated by a
colon(:).
# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks',
'for',
'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)
# To demonstrate aligning of spaces
String1 = "\n{0:^16} was founded in {1:<4}!".format("GeeksforGeeks",
2009)
print(String1)
Harwinder Singh Sohal
Python(INT-108)
Old style formatting was done without the use of format method by using % operator
# Python Program for
# Old Style Formatting
# of Integers
Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Python String constants
Built-In Function Description
Concatenation of the ascii_lowercase and ascii_uppercase
string.ascii_letters
constants.
string.ascii_lowercase Concatenation of lowercase letters
string.ascii_uppercase Concatenation of uppercase letters
string.digits Digit in strings
string.hexdigits Hexadigit in strings
string.letters concatenation of the strings lowercase and uppercase
string.lowercase A string must contain lowercase letters.
string.octdigits Octadigit in a string
string.punctuation ASCII characters having punctuation characters.
string.printable String of characters which are printable
Harwinder Singh Sohal
Python(INT-108)
Built-In Function Description
Returns True if a string ends with the given suffix otherwise
String.endswith()
returns False
Returns True if a string starts with the given prefix otherwise
String.startswith()
returns False
Returns “True” if all characters in the string are digits,
String.isdigit()
Otherwise, It returns “False”.
Returns “True” if all characters in the string are alphabets,
String.isalpha()
Otherwise, It returns “False”.
string.isdecimal() Returns true if all characters in a string are decimal.
one of the string formatting methods in Python3, which allows
str.format()
multiple substitutions and value formatting.
Returns the position of the first occurrence of substring in a
String.index
string
string.uppercase A string must contain uppercase letters.
string.whitespace A string containing all characters that are considered whitespace.
Method converts all uppercase characters to lowercase and vice
string.swapcase()
versa of the given string, and returns it
returns a copy of the string where all occurrences of a substring
replace()
is replaced with another substring.
Harwinder Singh Sohal
Python(INT-108)
Deprecated string functions
Built-In Function Description
string.Isdecimal Returns true if all characters in a string are decimal
String.Isalnum Returns true if all the characters in a given string are alphanumeric.
string.Istitle Returns True if the string is a title cased string
splits the string at the first occurrence of the separator and returns a
String.partition
tuple.
String.Isidentifier Check whether a string is a valid identifier or not.
String.len Returns the length of the string.
Returns the highest index of the substring inside the string if
String.rindex
substring is found.
String.Max Returns the highest alphabetical character in a string.
String.min Returns the minimum alphabetical character in a string.
String.splitlines Returns a list of lines in the string.
string.capitalize Return a word with its first character capitalized.
string.expandtabs Expand tabs in a string replacing them by one or more spaces
string.find Return the lowest indexing a sub string.
Harwinder Singh Sohal
Python(INT-108)
Built-In Function Description
string.rfind find the highest index.
Return the number of (non-overlapping) occurrences of substring sub
string.count
in string
Return a copy of s, but with upper case, letters converted to lower
string.lower
case.
Return a list of the words of the string, If the optional second
string.split
argument sep is absent or None
string.rsplit() Return a list of the words of the string s, scanning s from the end.
rpartition() Method splits the given string into three parts
Return a list of the words of the string when only used with two
string.splitfields
arguments.
Concatenate a list or tuple of words with intervening occurrences of
string.join
sep.
It returns a copy of the string with both leading and trailing white
string.strip()
spaces removed
string.lstrip Return a copy of the string with leading white spaces removed.
string.rstrip Return a copy of the string with trailing white spaces removed.
string.swapcase Converts lower case letters to upper case and vice versa.
Harwinder Singh Sohal
Python(INT-108)
Built-In Function Description
string.translate Translate the characters using table
string.upper lower case letters converted to upper case.
string.ljust left-justify in a field of given width.
string.rjust Right-justify in a field of given width.
string.center() Center-justify in a field of given width.
Pad a numeric string on the left with zero digits until the given width
string-zfill
is reached.
Return a copy of string s with all occurrences of substring old
string.replace
replaced by new.
Returns the string in lowercase which can be used for caseless
string.casefold()
comparisons.
Encodes the string into any encoding supported by Python. The
string.encode
default encoding is utf-8.
string.maketrans Returns a translation table usable for str.translate()
Advantages of String in Python:
Strings are used at a larger scale i.e. for a wide areas of operations such as
storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
Python has a rich set of string methods that allow you to manipulate and work
with strings in a variety of ways. These methods make it easy to perform
common tasks such as converting strings to uppercase or lowercase, replacing
substrings, and splitting strings into lists.
Strings are immutable, meaning that once you have created a string, you cannot
change it. This can be beneficial in certain situations because it means that you
can be confident that the value of a string will not change unexpectedly.
Harwinder Singh Sohal
Python(INT-108)
Python has built-in support for strings, which means that you do not need to
import any additional libraries or modules to work with strings. This makes it
easy to get started with strings and reduces the complexity of your code.
Python has a concise syntax for creating and manipulating strings, which makes
it easy to write and read code that works with strings.
Drawbacks of String in Python:
When we are dealing with large text data, strings can be inefficient. For instance,
if you need to perform a large number of operations on a string, such as
replacing substrings or splitting the string into multiple substrings, it can be slow
and consume a lot resources.
Strings can be difficult to work with when you need to represent complex data
structures, such as lists or dictionaries. In these cases, it may be more efficient to
use a different data type, such as a list or a dictionary, to represent the data.
Python string length | len()
Python len() function returns the length of the string.
Python len() Syntax
Syntax: len(string)
Return: It returns an integer which is the length of the string.
Python len() Example
len() methods with string in Python.
string = "Geeksforgeeks"
print(len(string))
Example 1: Len() function with tuples and string
Here we are counting length of the tuples and list.
# Python program to demonstrate the use of
# len() method
# with tuple
tup = (1,2,3)
print(len(tup))
# with list
l = [1,2,3,4]
print(len(l))
Harwinder Singh Sohal
Python(INT-108)
Example 2: Python len() TypeError
print(len(True))
Example 3: Python len() with dictionaries and sets
# Python program to demonstrate the use of
# len() method
dic = {'a':1, 'b': 2}
print(len(dic))
s = { 1, 2, 3, 4}
print(len(s))
Example 4: Python len() with custom objects
class Public:
def __init__(self, number):
self.number = number
def __len__(self):
return self.number
obj = Public(12)
print(len(obj))
Time complexity :
len() function has time complexity of O(1). in average and amortized case
String Slicing in Python
Python slicing is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Harwinder Singh Sohal
Python(INT-108)
How String slicing in Python works
For understanding slicing we will use different methods, here we will cover 2 methods of
string slicing, one using the in-build slice() method and another using the [:] array slice.
String slicing in Python is about obtaining a sub-string from the given string by slicing it
respectively from start to end.
Python slicing can be done in two ways:
Using a slice() method
Using the array slicing [:: ] method
Index tracker for positive and negative index: String indexing and slicing in python.
Here, the Negative comes into consideration when tracking the string in reverse.
Method 1: Using the slice() method
The slice() constructor creates a slice object representing the set of indices specified by
range(start, stop, step).
Syntax:
slice(stop)
slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index
where the slicing of object stops. step: It is an optional argument that determines the
increment between each index for slicing. Return Type: Returns a sliced object containing
elements in the given range only.
Example:
# Python program to demonstrate
# string slicing
# String slicing
Harwinder Singh Sohal
Python(INT-108)
String = 'ASTRING'
# Using slice constructor
s1 = slice(3)
s2 = slice(1, 5, 2)
s3 = slice(-1, -12, -2)
print("String slicing")
print(String[s1])
print(String[s2])
print(String[s3])
Method 2: Using the List/array slicing [ :: ] method
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy
and convenient way to slice a string using list slicing and Array slicing both syntax-wise
and execution-wise. A start, end, and step have the same mechanism as the slice()
constructor.
Below we will see string slicing in Python with examples.
Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example 1:
In this example, we will see slicing in python list the index start from 0 indexes and ending
with a 2 index(stops at 3-1=2 )
# Python program to demonstrate
# string slicing
# String slicing
String = 'GEEKSFORGEEKS'
Harwinder Singh Sohal
Python(INT-108)
# Using indexing sequence
print(String[:3])
Example 2:
In this example, we will see the example of starting from 1 index and ending with a 5
index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing
string by character.
# Python program to demonstrate
# string slicing
# String slicing
String = 'GEEKSFORGEEKS'
# Using indexing sequence
print(String[1:5:2])
Example 2:
In this example, we will see the example of starting from 1 index and ending with a 5
index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing
string by character.
# Python program to demonstrate
# string slicing
# String slicing
String = 'GEEKSFORGEEKS'
# Using indexing sequence
print(String[1:5:2])
Example 4:
In this example, the whole string is printed in reverse order.
# Python program to demonstrate
Harwinder Singh Sohal
Python(INT-108)
# string slicing
# String slicing
String = 'GEEKSFORGEEKS'
# Prints string in reverse
print(String[::-1])
Using islice()
The islice() is a built-in function defined in itertools module. It is used to get an iterator
which is an index-based slicing of any iterable. It works like a standard slice but returns an
iterator.
Syntax:
itertools.islice(iterable, start, stop[, step])
Parameters: iterable: Any iterable sequence like list, string, tuple etc. start: The start index
from where the slicing of iterable starts. stop: The end index from where the slicing of
iterable ends. step: An optional argument. It specifies the gap between each index for
slicing. Return Type: Return an iterator from the given iterable sequence.
Example:
# Python program to demonstrate
# islice()
import itertools
# Using islice()
String = 'GEEKSFORGEEKS'
# prints characters from 3 to 7 skipping one character.
print(''.join(itertools.islice(String, 3, 7)))
#This code is contributed by Edula Vinay Kumar Reddy
Reverse string in Python (6 different ways)
Python string library doesn’t support the in-built “reverse()” as done by other python
containers like list, hence knowing other methods to reverse string can prove to be useful.
This article discusses several ways to achieve it in Python.
Example:
Input: Geeksforgeeks
Harwinder Singh Sohal
Python(INT-108)
Output: skeegrofskeeG
Reverse a string in Python using a loop
In this example, we call a function to reverse a string, which iterates to every element and
intelligently joins each character in the beginning so as to obtain the reversed string.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
def reverse(s):
str = ""
for i in s:
str = i + str
return str
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using loops) is : ", end="")
print(reverse(s))
Reverse a string in Python using recursion
The string is passed as an argument to a recursive function to reverse the string. In the
function, the base condition is that if the length of the string is equal to 0, the string is
returned. If not equal to 0, the reverse function is recursively called to slice the part of the
string except the first character and concatenate the first character to the end of the sliced
string. ‘
Implementation
def reverse(s):
if len(s) == 0:
return s
else:
return reverse(s[1:]) + s[0]
Harwinder Singh Sohal
Python(INT-108)
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using recursion) is : ", end="")
print(reverse(s))
Time complexity: O(n), for recursion to reverse
Auxiliary Space: O(n), for recursion call stack
Reverse string in Python using stack
An empty stack is created. One by one character of the string is pushed to the stack. One by
one all characters from the stack are popped and put back to a string.
Time complexity: O(n)
Auxiliary Space: O(n)
Implementation:
# Function to create an empty stack. It
# initializes size of stack as 0
def createStack():
stack = []
return stack
# Function to determine the size of the stack
def size(stack):
return len(stack)
# Stack is empty if the size is 0
def isEmpty(stack):
if size(stack) == 0:
return true
# Function to add an item to stack . It
# increases size by 1
def push(stack, item):
stack.append(item)
# Function to remove an item from stack.
# It decreases size by 1
def pop(stack):
if isEmpty(stack):
Harwinder Singh Sohal
Python(INT-108)
return
return stack.pop()
# A stack based function to reverse a string
def reverse(string):
n = len(string)
# Create a empty stack
stack = createStack()
# Push all characters of string to stack
for i in range(0, n, 1):
push(stack, string[i])
# Making the string empty since all
# characters are saved in stack
string = ""
# Pop all characters of string and put
# them back to string
for i in range(0, n, 1):
string += pop(stack)
return string
# Driver code
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using stack) is : ", end="")
print(reverse(s))
Reverse string in Python using an extended slice
Extended slice offers to put a “step” field as [start, stop, step], and giving no field as start
and stop indicates default to 0 and string length respectively, and “-1” denotes starting from
the end and stop at the start, hence reversing a string.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
# Function to reverse a string
def reverse(string):
string = string[::-1]
Harwinder Singh Sohal
Python(INT-108)
return string
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using extended slice syntax) is : ", end="")
print(reverse(s))
Reverse string in Python using reversed() method
The reversed() returns the reversed iterator of the given string and then its elements are
joined empty string separated using join(). And reversed order string is formed.
Time complexity: O(n)
Auxiliary Space: O(n)
Implementation:
# Python code to reverse a string
# using reversed()
# Function to reverse a string
def reverse(string):
string = "".join(reversed(string))
return string
s = "Geeksforgeeks"
print("The original string is : ", end="")
print(s)
print("The reversed string(using reversed) is : ", end="")
print(reverse(s))
Harwinder Singh Sohal
Python(INT-108)
Reverse string in Python using list comprehension()
List comprehension creates the list of elements of a string in reverse order and then its
elements are joined using join(). And reversed order string is formed.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
# Function to reverse a string
def reverse(string):
string = [string[i] for i in range(len(string)-1, -1, -1)]
return "".join(string)
s = "Geeksforgeeks"
print("The original string is : ", s)
print("The reversed string(using reversed) is : ", reverse(s))
Reverse string in Python using the function call
Function to reverse a string by converting string to list then reversed it and again convert it
to string.
Time complexity: O(n)
Auxiliary Space: O(1)
Implementation:
# Function to reverse a string
# by converting string to list
# then reversed it and again convert it to string
def reverse(string):
string = list(string)
string.reverse()
return "".join(string)
s = "Geeksforgeeks"
print("The original string is : ", s)
Harwinder Singh Sohal
Python(INT-108)
print("The reversed string(using reversed) is : ", reverse(s))
# This code is contributed by Susobhan AKhuli
Ways to print escape characters in Python
Escape characters are characters that are generally used to perform certain tasks and their
usage in code directs the compiler to take a suitable action mapped to that character.
Example :
'\n' --> Leaves a line
'\t' --> Leaves a space
# Python code to demonstrate escape character
# string
ch = "I\nLove\tGeeksforgeeks"
print ("The string after resolving escape character is : ")
print (ch)
But in certain cases it is desired not to resolve escapes, i.e the entire unresolved string has
to be printed. These are achieved by following ways.
Using repr()
This function returns a string in its printable format, i.e doesn’t resolve the escape
sequences.
# Python code to demonstrate printing
# escape characters from repr()
# initializing target string
ch = "I\nLove\tGeeksforgeeks"
print ("The string without repr() is : ")
print (ch)
Harwinder Singh Sohal
Python(INT-108)
print ("\r")
print ("The string after using repr() is : ")
print (repr(ch))
Using “r/R”
Adding “r” or “R” to the target string triggers a repr() to the string internally and stops from
the resolution of escape characters.
# Python code to demonstrate printing
# escape characters from "r" or "R"
# initializing target string
ch = "I\nLove\tGeeksforgeeks"
print ("The string without r / R is : ")
print (ch)
print ("\r")
# using "r" to prevent resolution
ch1 = r"I\nLove\tGeeksforgeeks"
print ("The string after using r is : ")
print (ch1)
print ("\r")
# using "R" to prevent resolution
ch2 = R"I\nLove\tGeeksforgeeks"
Harwinder Singh Sohal
Python(INT-108)
print ("The string after using R is : ")
print (ch2)
Using raw string notation:
Approach:
We can also use the raw string notation to print escape characters in Python. We just need
to add the letter “r” before the opening quote of the string.
Algorithm:
Define a raw string variable with the required escape sequence.
Use the print() function to print the string.
string = "I\nLove\tGeeks\tforgeeks"
print(string)
Python 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.
Example of list in Python
Here we are creating Python List using [].
Var = ["Geeks", "for", "Geeks"]
print(Var)
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
# Python program to demonstrate
# Creation of List
# Creating a List
Harwinder Singh Sohal
Python(INT-108)
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])
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.
# 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
Harwinder Singh Sohal
Python(INT-108)
# 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)
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
# 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])
Example 2: Accessing elements from a multi-dimensional list
# 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
Harwinder Singh Sohal
Python(INT-108)
# index number
print("Accessing a element from a Multi-Dimensional list")
print(List[0][1])
print(List[1][0])
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.
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])
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.
# Creating a List
List1 = []
print(len(List1))
Harwinder Singh Sohal
Python(INT-108)
# Creating a List of numbers
List2 = [10, 20, 14]
print(len(List2))
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:
# 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
Example 2:
# 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)
Harwinder Singh Sohal
Python(INT-108)
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.
# 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
Harwinder Singh Sohal
Python(INT-108)
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)
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).
# 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')
Harwinder Singh Sohal
Python(INT-108)
print("\nList after performing Insert Operation: ")
print(List)
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.
# 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)
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.
# Reversing a list
mylist = [1, 2, 3, 4, 5, 'Geek', 'Python']
Harwinder Singh Sohal
Python(INT-108)
mylist.reverse()
print(mylist)
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)
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:
# 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)
Harwinder Singh Sohal
Python(INT-108)
print("\nList after Removal of two elements: ")
print(List)
Example 2:
# 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)
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.
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
Harwinder Singh Sohal
Python(INT-108)
# Set using the pop() method
List.pop(2)
print("\nList after popping a specific element: ")
print(List)
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.
Harwinder Singh Sohal
Python(INT-108)
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.
# 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)
Harwinder Singh Sohal
Python(INT-108)
Negative index List slicing
# 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)
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 ]
Harwinder Singh Sohal
Python(INT-108)
Example:
# 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)
# 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)
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
Harwinder Singh Sohal
Python(INT-108)
Function Description
Index() Returns the index of the first matched item
Count() Returns the count of the number of items passed as an 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 index is provided,
pop()
it removes and returns the last item.
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 the list elements
reduce()
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 the given
ord()
Unicode character
cmp() This function returns 1 if the first list is “greater” than the second list
max() return maximum element of a given list
Harwinder Singh Sohal
Python(INT-108)
Function Description
min() return minimum element of a given list
all() Returns true if all element is true or if the list is empty
any() return true if any element of the list is true. if the list is 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 the list elements
accumulate()
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 function to each item
map()
of a given iterable
This function can have any number of arguments but only one expression,
lambda()
which is evaluated and returned.
Python | Create list of numbers with given range
Given two numbers r1 and r2 (which defines the range), write a Python program to create a
list with the given range (inclusive).
Examples:
Input : r1 = -1, r2 = 1
Output : [-1, 0, 1]
Input : r1 = 5, r2 = 9
Output : [5, 6, 7, 8, 9]
Naive Approach using a loop
A naive method to create a list within a given range is to first create an empty list and
append the successor of each integer in every iteration of for loop.
# Python3 Program to Create list
Harwinder Singh Sohal
Python(INT-108)
# with integers within given range
def createList(r1, r2):
# Testing if range r1 and r2
# are equal
if (r1 == r2):
return r1
else:
# Create empty list
res = []
# loop to append successors to
# list until r2 is reached.
while(r1 < r2+1 ):
res.append(r1)
r1 += 1
return res
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))
Using List comprehension
We can also use list comprehension for the purpose. Just iterate ‘item’ in a for loop
from r1 to r2 and return all ‘item’ as list. This will be a simple one liner code.
# Python3 Program to Create list
# with integers within given range
Harwinder Singh Sohal
Python(INT-108)
def createList(r1, r2):
return [item for item in range(r1, r2+1)]
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))
Using Python range()
Python comes with a direct function range() which creates a sequence of numbers from
start to stop values and print each item in the sequence. We use range() with r1 and r2 and
then convert the sequence into list.
# Python3 Program to Create list
# with integers within given range
def createList(r1, r2):
return list(range(r1, r2+1))
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))
Using itertools:
You can also use the range function in combination with the itertools module’s chain
function to create a list of numbers with a given range. This can be done as follows:
# Python3 Program to Create list
# with integers within given range
import itertools
r1=-5
r2=5
#using the chain function from the itertools module
Harwinder Singh Sohal
Python(INT-108)
numbers = list(itertools.chain(range(r1, r2+1)))
print(numbers)
#This code is contributed by Edula Vinay Kumar Reddy
Using numpy.arange()
Python numpy.arange() returns a list with evenly spaced elements as per the interval. Here
we set the interval as 1 according to our need to get the desired output.
# Python3 Program to Create list
# with integers within given range
import numpy as np
def createList(r1, r2):
return np.arange(r1, r2+1, 1)
# Driver Code
r1, r2 = -1, 1
print(createList(r1, r2))
Using numpy to create list of numbers with given range
Here we are creating a list of numbers from a given range with the defined increment.
import numpy as np
def fun(start, end, step):
num = np.linspace(start, end,(end-start)
*int(1/step)+1).tolist()
return [round(i, 2) for i in num]
print(fun(1,5,0.5))
Using Recursion
Another approach to create a list of numbers within a given range is to use recursion. This
involves defining a recursive function that takes in the current range and the list to be
Harwinder Singh Sohal
Python(INT-108)
returned, and then appending the current range to the list and calling the function again with
the next range until the end of the range is reached.
def create_list(r1, r2, lst):
# Base case: if r1 is equal to r2, return the list
if r1 == r2+1:
return lst
# Otherwise, append r1 to the list and call the function again with r1 + 1
else:
lst.append(r1)
return create_list(r1 + 1, r2, lst)
# Test the function
print(create_list(5, 9, [])) # [5, 6, 7, 8, 9]
print(create_list(-1, 1, [])) # [-1, 0, 1]
#This code is contributed by Edula Vinay Kumar Reddy
This approach has a time complexity of O(n) and an auxiliary space of O(n), where n is the
number of elements in the list.
Approach 5: Using map() and lambda function
In this approach, we use map() and a lambda function to generate a list of numbers within
the given range. map() applies the lambda function to each element in the sequence and
returns a map object. We convert the map object to a list and return it.
Algorithm
Use map() and a lambda function to generate a list of numbers within the given range.
Convert the map object to a list and return it.
def create_list(r1, r2):
return list(map(lambda x: x, range(r1, r2+1)))
# Test the function
print(create_list(5, 9)) # [5, 6, 7, 8, 9]
print(create_list(-1, 1)) # [-1, 0, 1]
Harwinder Singh Sohal
Python(INT-108)
Time Complexity: O(r2-r1) where r1 and r2 are the given range.
Space Complexity: O(r2-r1) where r1 and r2 are the given range.
Python Program to Accessing index and value in list
There are various methods to access the elements of a list, but sometimes we may require to
access an element along with the index on which it is found. Let’s see all the different ways
of accessing both index and value in a list.
Accessing index and value in list Using Naive method
This is the most generic method that can be possibly employed to perform this task of
accessing the index along with the value of the list elements. This is done using a loop.
# Python3 code to demonstrate
# to get index and value
# using naive method
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
# using naive method to
# get index and value
print("List index-value are : ")
for i in range(len(test_list)):
print(i, end=" ")
print(test_list[i])
Accessing index and value in list Using list comprehension
This method works in similar way as the above method but uses the list comprehension
technique for the same, this reduces the possible lines of code to be written and hence saves
time.
# Python3 code to demonstrate
# to get index and value
# using list comprehension
Harwinder Singh Sohal
Python(INT-108)
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
# using list comprehension to
# get index and value
print("List index-value are : ")
print([list((i, test_list[i])) for i in range(len(test_list))])
Accessing index and value in list Using enumerate()
This is the most elegant method to perform this particular problem and is highly
recommended to be used in case we require to get the index along with the value in the list.
This method enumerates for index along with its value.
# Python3 code to demonstrate
# to get index and value
# using enumerate
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
# using enumerate to
# get index and value
print("List index-value are : ")
for index, value in enumerate(test_list):
print(index, value)
Harwinder Singh Sohal
Python(INT-108)
Accessing index and value in list Using zip()
Another method that is basically used to bind the index with the corresponding value, zip()
can also be possibly used to get index along with its value.
# Python3 code to demonstrate
# to get index and value
# using zip()
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
# using zip() to
# get index and value
print("List index-value are : ")
for index, value in zip(range(len(test_list)), test_list):
print(index, value)
Accessing index and value in list Using numpy.ndenumerate()
Approach:
1. Import the numpy module.
2. Initialize the list.
3. Convert the list into a numpy array.
4. Iterate over the numpy array using the numpy.ndenumerate() function.
5. Print the index and value of each element.
import numpy as np
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
Harwinder Singh Sohal
Python(INT-108)
# using numpy.ndenumerate() to get index and value
print("List index-value are : ")
for index, value in np.ndenumerate(test_list):
print(index[0], value)
Accessing index and value in list Using heapq
Approach:
1. Import the heapq module.
2. Initialize the list test_list with some values.
3. Print out the original list test_list.
4. Create an empty list heap to store the index and value pairs in a heap.
5. Iterate over the list test_list using enumerate.
6. For each index and value pair, use heapq.heappush() to add the pair to the heap
list.
7. heappush() maintains the heap property so that the smallest element in the heap
is always at the root.
8. Enter a while loop that runs until there are no more elements in the heap.
9. Inside the loop, use heapq.heappop() to retrieve the smallest element from the
heap.
10. heappop() removes the element from the heap and returns it as a tuple containing
the index and value of an element in the original list.
11. Print out the index and value of the element.
import heapq
# initializing list
test_list = [1, 4, 5, 6, 7]
# Printing list
print("Original list is : " + str(test_list))
# using heapq to get index and value
print("List index-value are : ")
heap = []
for index, value in enumerate(test_list):
heapq.heappush(heap, (index, value))
Harwinder Singh Sohal
Python(INT-108)
while heap:
index, value = heapq.heappop(heap)
print(index, value)
How To Find the Length of a List in Python
List being an integral part of Python day-to-day programming has to be learned by all
Python users and having a knowledge of its utility and operations is essential and always a
plus. So this article discusses one such utility of finding the no. of elements in a list
using Python.
Example:
Input: lst = [10,20,30,40]
Output: 4
Explanation: The output is 4 because the length of the list is 4.
Get the Length of a List in Python using len()
Python len() function is an inbuilt function in Python. It can be used to find the length of an
object by passing the object within the parentheses of the len function.
# Python len()
li = [10, 20, 30]
n = len(li)
print("The length of list is: ", n)
Find the Length of a List in Python Naive Method
In this method, one just runs a loop and increases the counter till the last element of the list
to know its count. This is the most basic strategy that can be possibly employed in the
absence of other present techniques.
Python3
# Python code to demonstrate
# length of list
# using naive method
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
print("The list is : " + str(test_list))
Harwinder Singh Sohal
Python(INT-108)
# Finding length of list
# using loop
# Initializing counter
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
# Printing length of list
print("Length of list using naive method is : " + str(counter))
Find the Length of a List in Python using length_hint()
This technique is a lesser-known technique for finding list length. This particular method is
defined in the operator class and it can also tell the no. of elements present in the list. Here,
we are finding length of list using len() and length_hint()
# Python code to demonstrate
# length of list
# using len() and length_hint
from operator import length_hint
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
print("The list is : " + str(test_list))
# Finding length of list
# using len()
list_len = len(test_list)
Harwinder Singh Sohal
Python(INT-108)
# Finding length of list
# using length_hint()
list_len_hint = length_hint(test_list)
# Printing length of list
print("Length of list using len() is : " + str(list_len))
print("Length of list using length_hint() is : " + str(list_len_hint))
Find the Length of a List in Python using sum()
Use iteration inside the sum and with each iteration adds one and at the end of the iteration,
we get the total length of the list.
# Python code to demonstrate
# length of list
# using sum()
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
print("The list is : " + str(test_list))
# Finding length of list
# using sum()
list_len = sum(1 for i in test_list)
# Printing length of list
print("Length of list using len() is : " + str(list_len))
print("Length of list using length_hint() is : " + str(list_len))
Output:
Harwinder Singh Sohal
Python(INT-108)
The list is : [1, 4, 5, 7, 8]
Length of list using len() is : 5
Length of list using length_hint() is : 5
Find the Length of a List in Python using a List Comprehension
Initialize a list called test_list with some values then Initialize a variable called length to 0.
Use a list comprehension to generate a sequence of ones for each element in the test_list.
This will create a list of ones with the same length as the test_list. Now use
the sum() function to sum all the ones in the list generated by the list comprehension.
Assign the sum to the length variable. Print the length variable.
# Define the list to be used for the demonstration
test_list = [1, 4, 5, 7, 8]
# Calculate the length of the list using a list comprehension and the sum function
# The list comprehension generates a sequence of ones for each element in the list
# The sum function then sums all the ones to give the length of the list
length = sum(1 for _ in test_list)
# Print the length of the list
print("Length of list using list comprehension is:", length)
Time Complexity: The list comprehension creates a new list with a length equal to the
length of the test_list. The sum() function then iterates over this list to compute the sum.
Therefore, the time complexity of this algorithm is O(N), where N is the length of the
test_list.
Auxiliary Space: The algorithm creates a new list of ones with a length equal to the length
of the test_list using the list comprehension. Therefore, the auxiliary space complexity is
also O(N), where N is the length of the test_list.
Find the Length of a List in Python using recursion
This function takes a list lst as input and recursively calls itself, passing in a slice of the list
that excludes the first element until the list is empty. The base case is when the list is
empty, in which case the function returns 0. Otherwise, it adds 1 to the result of calling the
function on the rest of the list.
# Define a function to count the number of elements in a list using recursion
def count_elements_recursion(lst):
# Base case: if the list is empty, return 0
if not lst:
return 0
Harwinder Singh Sohal
Python(INT-108)
# Recursive case: add 1 to the count of the remaining elements in the list
return 1 + count_elements_recursion(lst[1:])
# Test the function with a sample list
lst = [1, 2, 3, 4, 5]
print("The length of the list is:", count_elements_recursion(lst))
# Output: The length of the list is: 5
Time complexity: O(n) where n is the length of the list. This is because the function makes
n recursive calls, each taking O(1) time, and there is also O(1) work done at each level
outside of the recursive call.
Space complexity: O(n) where n is the length of the list. This is because the function
creates n stack frames on the call stack due to the recursive calls.
Find the Length of a List in Python using enumerate function
Python Enumerate() method adds a counter to an iterable and returns it in a form of an
enumerating object.
# python code to find the length
# of list using enumerate function
list1 = [1, 4, 5, 7, 8]
s=0
for i, a in enumerate(list1):
s += 1
print(s)
Find the Length of a List in Python using Collections
Alternatively, you can also use the sum() function along with the values() method of
the Collections Counter object to get the length of the list.
from collections import Counter
# Initializing list
Harwinder Singh Sohal
Python(INT-108)
test_list = [1, 4, 5, 7, 8]
# Finding length of list using Counter()
list_len = sum(Counter(test_list).values())
print("Length of list using Counter() is:", list_len)
# This code is contributed by Edula Vinay Kumar Reddy
Naive vs Python len() vs Python length_hint()
When choosing amongst alternatives it’s always necessary to have a valid reason why to
choose one over another. This section does a time analysis of how much time it takes to
execute all of them to offer a better choice to use.
from operator import length_hint
import time
# Initializing list
test_list = [1, 4, 5, 7, 8]
# Printing test_list
print("The list is : " + str(test_list))
# Finding length of list
# using loop
# Initializing counter
start_time_naive = time.time()
counter = 0
for i in test_list:
# incrementing counter
counter = counter + 1
end_time_naive = str(time.time() - start_time_naive)
Harwinder Singh Sohal
Python(INT-108)
# Finding length of list
# using len()
start_time_len = time.time()
list_len = len(test_list)
end_time_len = str(time.time() - start_time_len)
# Finding length of list
# using length_hint()
start_time_hint = time.time()
list_len_hint = length_hint(test_list)
end_time_hint = str(time.time() - start_time_hint)
# Printing Times of each
print("Time taken using naive method is : " + end_time_naive)
print("Time taken using len() is : " + end_time_len)
print("Time taken using length_hint() is : " + end_time_hint)
length_hint() > len(), but the time taken depends highly on the OS and several of its
parameter. In two consecutive runs, you may get contrasting results, in fact sometimes
naive takes the least time out of three. All the possible 6 permutations are possible.
Harwinder Singh Sohal
Python(INT-108)
Get a list as input from user in Python
We often encounter a situation when we need to take a number/string as input from the
user. In this article, we will see how to get input a list from the user using Python.
Example:
Input : n = 4, ele = 1 2 3 4
Output : [1, 2, 3, 4]
Input : n = 6, ele = 3 4 1 7 9 6
Output : [3, 4, 1, 7, 9, 6]
Method 1: A basic example using Loop
# creating an empty list
lst = []
# number of elements as input
n = int(input("Enter number of elements : "))
# iterating till the range
for i in range(0, n):
ele = int(input())
# adding the element
lst.append(ele)
print(lst)
Method 2: With exception handling
# try block to handle the exception
try:
my_list = []
while True:
my_list.append(int(input()))
Harwinder Singh Sohal
Python(INT-108)
# if the input is not-integer, just print the list
except:
print(my_list)
Method 3: Using map()
# number of elements
n = int(input("Enter number of elements : "))
# Below line read inputs from user using map() function
a = list(map(int,
input("\nEnter the numbers : ").strip().split()))[:n]
print("\nList is - ", a)
Method 4: List of lists as input
lst = []
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = [input(), int(input())]
lst.append(ele)
print(lst)
Method 5: Using List Comprehension and Typecasting
# For list of integers
lst1 = []
# For list of strings/chars
lst2 = []
Harwinder Singh Sohal
Python(INT-108)
lst1 = [int(item) for item in input("Enter \
the list items : ").split()]
lst2 = [item for item in input("Enter \
the list items : ").split()]
print(lst1)
print(lst2)
Python Tuples
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.
# 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
Harwinder Singh Sohal
Python(INT-108)
# 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)
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.
# 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
Harwinder Singh Sohal
Python(INT-108)
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)
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.
# 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
Harwinder Singh Sohal
Python(INT-108)
a, b, c = Tuple1
print("\nValues after unpacking: ")
print(a)
print(b)
print(c)
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.
# 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)
Harwinder Singh Sohal
Python(INT-108)
# Printing Final Tuple
print("\nTuples after Concatenation: ")
print(Tuple3)
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.
# 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])
Harwinder Singh Sohal
Python(INT-108)
# Printing elements of a Range
print("\nPrinting elements between Range 4-9: ")
print(Tuple1[4:9])
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.
# 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
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, return
any() false
Harwinder Singh Sohal
Python(INT-108)
Built-in
Function Description
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 we generally use ‘tuples’ for heterogeneous (different)
both lists and tuples: data types and ‘lists’ for homogeneous (similar) data
count(), Index() types.
Harwinder Singh Sohal
Python(INT-108)
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 as a
be nested. key for a dictionary.
Create a tuple from string and list – Python
Sometimes, we can have a problem in which we need to construct a new container with
elements from different containers. This kind of problem can occur in domains in which we
use different types of data. Let’s discuss ways to convert string and list data to tuple.
Create a tuple from string and list Using List conversion to tuple + tuple()
In this method, we convert the string to list and then append to target list and then convert
this result list to tuple using tuple().
Python3
# Python3 code to demonstrate working of
# Construct tuple from string and list
# using list conversion to tuple + tuple()
# initialize list and string
test_list = ["gfg", "is"]
test_str = "best"
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Construct tuple from string and list
# using list conversion to tuple + tuple()
res = tuple(test_list + [test_str])
# printing result
Harwinder Singh Sohal
Python(INT-108)
print("The aggregated tuple is : " + str(res))
Create a tuple from string and list Using Tuple conversion to tuple + tuple()
This is another way in which this task can be performed. In this, we convert the string and
list both to tuple and add them to result tuple. This method is more efficient than the above
method.
# Python3 code to demonstrate working of
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
# initialize list and string
test_list = ["is", "best"]
test_str = "gfg"
# printing original list and tuple
print("The original list : " + str(test_list))
print("The original string : " + test_str)
# Construct tuple from string and list
# using tuple conversion to tuple + tuple()
res = (test_str, ) + tuple(test_list)
# printing result
print("The aggregated tuple is : " + str(res))
Create a tuple from string and list Using list+ tuple+ copy()+append()
Get the copy of original list and then append the original string to it later convert it to tuple
step-by-step algorithm
1. we first make a copy of the original list
2. we use the append() method to add the elements of the original string to the new list.
3. We then create a new tuple from the new list using the tuple() constructor.
4.The resulting tuple contains all the elements of the original list followed by the original
string.
Harwinder Singh Sohal
Python(INT-108)
# Define the original list and string
original_list = ['gfg', 'is']
original_string = 'best'
# Create a new list by extending the original list with the string
new_list = original_list.copy()
new_list.append(original_string)
# Create a new tuple from the new list using the tuple constructor
new_tuple = tuple(new_list)
# Print the output tuple
print("The aggregated tuple is :", new_tuple)
Create a tuple from string and list Using the + operator
In this approach, we use the + operator to concatenate the list and the string, and then
convert the result to a tuple using the tuple() constructor.
1.Concatenate the list and the string using the + operator.
2.Convert the concatenated result to a tuple using the tuple() constructor.
3.Return the tuple.
lst = ['gfg', 'is']
string = 'best'
result = tuple(lst + [string])
print(result)
Create a tuple from string and list Using extend method
The approach used here is to create a new list by extending the original list with the given
string and then convert the new list to a tuple using the built-in tuple() function
1. Start by defining a function that takes two arguments, a string, and a list.
2. Extend the given list with the given string using the extend() function.
3. Convert the extended list to a tuple using the tuple() function.
4. Return the tuple.
Harwinder Singh Sohal
Python(INT-108)
# Function to create a tuple
def create_tuple(string, lst):
lst.extend([string])
return tuple(lst)
# Driver Code
original_list = ['gfg', 'is']
original_string = 'best'
result = create_tuple(original_string, original_list)
print("The original list : ", original_list)
print("The original string : ", original_string)
print("The aggregated tuple is : ", result)
Access front and rear element of Python tuple
Sometimes, while working with records, we can have a problem in which we need to access
the initial and last data of a particular record. This kind of problem can have application in
many domains. Let’s discuss some ways in which this problem can be solved.
Method #1: Using Access Brackets We can perform the possible get of front and rear
element in tuple using the access brackets in similar way in which elements can be accessed
in list.
# Python3 code to demonstrate working of
# Accessing front and rear element of tuple
# using access brackets
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Accessing front and rear element of tuple
# using access brackets
res = (test_tup[0], test_tup[-1])
# printing result
print("The front and rear element of tuple are : " + str(res))
Harwinder Singh Sohal
Python(INT-108)
Method #2: Using itemegetter() This is yet another way in which this task can be
performed. In this, we access the elements using inbuilt function of itemgetter().
# Python3 code to demonstrate working of
# Accessing front and rear element of tuple
# using itemgetter()
from operator import itemgetter
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Accessing front and rear element of tuple
# using itemgetter()
res = itemgetter(0, -1)(test_tup)
# printing result
print("The front and rear element of tuple are : " + str(res))
Method #3: Using indexing
# Python3 code to demonstrate working of
# Accessing front and rear element of tuple
# using access brackets
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Accessing front and rear element of tuple
# using access brackets
res = (test_tup[0], test_tup[len(test_tup)-1])
# printing result
print("The front and rear element of tuple are : " + str(res))
Method#4: Using Unpacking tuple.
This method requires the *_ syntax, which is called “unpacking” in Python and allows you
to assign a specific portion of a tuple to a variable. In this case, the *_ syntax is used to
ignore the intermediate elements in the tuple.
# Python3 code to demonstrate working of
# Accessing front and rear element of tuple
# using Unpacking the tuple
Harwinder Singh Sohal
Python(INT-108)
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Accessing front and rear element of tuple
# Unpacking the tuple
front, *_, rear = test_tup
# Storing the front and rear elements
res = (front, rear)
# printing result
print("The front and rear element of tuple are : " + str(res))
# this code contributed by tvsk.
Method #5: Using slicing
This program demonstrates how to access the first and last elements of a tuple using slicing
in Python. It initializes a tuple, extracts its first and last elements using slicing, stores them
in a new tuple, and prints the result.
Approach:
1. Initialize the tuple “test_tup” with values (10, 4, 5, 6, 7).
2. Print the original tuple “test_tup”.
3. Use indexing/slicing to access the first element of the tuple and store it in a
variable “front”.
4. Use negative indexing/slicing to access the last element of the tuple and store it
in a variable “rear”.
5. Create a new tuple “res” with the front and rear elements stored in the previous
steps.
6. Print the new tuple “res” containing the front and rear elements of the original
tuple.
# Python3 code to demonstrate working of
# Accessing front and rear element of tuple
# using slicing
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Accessing front and rear element of tuple
Harwinder Singh Sohal
Python(INT-108)
# using slicing
front = test_tup[0]
rear = test_tup[-1]
# Storing the front and rear elements
res = (front, rear)
# printing result
print("The front and rear element of tuple are : " + str(res))
Method #6: Using tuple() constructor and concatenation
In this method, first retrieve the first and last elements of the original tuple using indexing.
Then, create two new tuples containing these elements using the tuple() constructor.
Finally, concatenate these two tuples using the + operator to create a new tuple containing
both elements.
test_tup = (10, 4, 5, 6, 7)
front = test_tup[0]
rear = test_tup[-1]
res = tuple([front]) + tuple([rear])
print("The front and rear element of tuple are : " + str(res))
Method #7: Using List Comprehension
Create a list comprehension with the first and last element of the tuple.
Convert the resulting list to a tuple using the tuple() constructor.
# initialize tuple
test_tup = (10, 4, 5, 6, 7)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Using List Comprehension
res = tuple([test_tup[i] for i in [0,-1]])
# printing result
print("The front and rear element of tuple are : " + str(res))
Python | Ways to concatenate tuples
Method #1 : Using + operator This is the most Pythonic and recommended method to
perform this particular task. In this, we add two tuples and return the concatenated tuple.
No previous tuple is changed in this process.
step-by-step approach :
1. Initialize two tuples with elements (1, 3, 5) and (4, 6) respectively and assign
them to the variables test_tup1 and test_tup2.
Harwinder Singh Sohal
Python(INT-108)
2. Print the original values of the two tuples using print() function and concatenate
them with the string using + operator.
3. Concatenate the two tuples test_tup1 and test_tup2 using + operator and assign
the result to a new variable res.
4. Print the concatenated tuple res using print() function and concatenate it with the
string using + operator.
5. End of the program.
# Python3 code to demonstrate working of
# Ways to concatenate tuples
# using + operator
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Ways to concatenate tuples
# using + operator
res = test_tup1 + test_tup2
# printing result
print("The tuple after concatenation is : " + str(res))
Method #2 : Using sum() This is yet another way in which this task can be performed. In
this, we add the tuples to one other using sum function.
# Python3 code to demonstrate working of
# Ways to concatenate tuples
# using sum()
# initialize tuples
Harwinder Singh Sohal
Python(INT-108)
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Ways to concatenate tuples
# using sum()
res = sum((test_tup1, test_tup2), ())
# printing result
print("The tuple after concatenation is : " + str(res))
Method #3: Using list() and extend() methods
# Python3 code to demonstrate working of
# Ways to concatenate tuples
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Ways to concatenate tuples
x = list(test_tup1)
y = list(test_tup2)
x.extend(y)
Harwinder Singh Sohal
Python(INT-108)
res = tuple(x)
# printing result
print("The tuple after concatenation is : " + str(res))
Method #4: Using itertools.chain() function
Algorithm
1. Import the itertools module.
2. Create the original tuples tuple1 and tuple2.
3. Use the itertools.chain() function to concatenate the tuples.
4. Convert the concatenated result to a tuple.
5. Print the concatenated tuple.
# Python program to concatenate tuples
import itertools
# original tuples
tuple1 = (1, 3, 5)
tuple2 = (4, 6)
# concatenate the tuples using itertools.chain()
tuple3 = tuple(itertools.chain(tuple1, tuple2))
# print the concatenated tuple
print("Concatenated tuple:", tuple3)
Method #5: Using the tuple() constructor and the * operator
This method uses the tuple() constructor to create a new tuple by concatenating the two
original tuples using the + operator, and then converts the result back to a tuple using the
tuple() constructor.
# Python3 code to demonstrate working of
# Ways to concatenate tuples
# using * operator
Harwinder Singh Sohal
Python(INT-108)
# initialize tuples
test_tup1 = (1, 3, 5)
test_tup2 = (4, 6)
# printing original tuples
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
# Ways to concatenate tuples
# using * operator and tuple() constructor
res = tuple(test_tup1 + test_tup2)
# printing result
print("The tuple after concatenation is : " + str(res))
.
METHOD 6: Using the += operator and the += method:
APPROACH:
In this approach, we use the += operator to concatenate the second tuple to the first tuple.
This modifies the first tuple in place. We can also use the += method of tuples to achieve
the same result.
ALGORITHM:
1.Create the first tuple t1.
2.Create the second tuple t2.
3.Use the += operator to concatenate t2 to t1.
4.Print the concatenated tuple t1
t1 = (1, 2, 3)
t2 = (4, 5, 6)
t1 += t2
print(t1) # Output: (1, 2, 3, 4, 5, 6)
Approach#7: Using reduce
Use a lambda function with reduce() function to concatenate two tuples.
Harwinder Singh Sohal
Python(INT-108)
Algorithm
1. Define a lambda function that takes two tuples as input and reduces them by
concatenation using the + operator.
2. Call the lambda function with the two input tuples as arguments using the reduce()
function.
3. Return the concatenated tuple.
from functools import reduce
concat_tuples = lambda t1, t2: reduce(lambda x, y: x + y, [t1, t2])
t1 = (1, 3, 5)
t2 = (4, 6)
concatenated_tuple = concat_tuples(t1, t2)
print(concatenated_tuple)
Python – Clearing a tuple
Method #1 : Using list() + clear() + tuple()
The combination of above 3 functions can be used to perform this task. In this, we
interconvert the tuple to list, clear it and again convert to tuple using tuple().
# Python3 code to demonstrate
# Clearing a tuple
# using list() + tuple() + clear()
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Clearing a tuple
# using list() + tuple() + clear()
temp = list(test_tup)
temp.clear()
test_tup = tuple(temp)
# print result
print("The tuple after clearing values : " + str(test_tup))
Method #2 : Reinitialization using tuple()
Another straight forward way to perform this task is to reinitialize tuple using tuple() which
will return empty tuple.
# Python3 code to demonstrate
Harwinder Singh Sohal
Python(INT-108)
# Clearing a tuple
# using Reinitialization + tuple()
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Clearing a tuple
# using Reinitialization + tuple()
test_tup = tuple()
# print result
print("The tuple after clearing values : " + str(test_tup))
Method #3: Using * operator
This method uses the * operator to create a new tuple with zero copies of the original tuple.
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
# Clearing a tuple using * operator
test_tup = test_tup * 0
# print result
print("The tuple after clearing values : " + str(test_tup))
#This code is contributed by Edula Vinay Kumar Reddy
Method #4: Using slicing and concatenation
Initialize a tuple called test_tup with values (1, 5, 3, 6, 8).
Print the original tuple using the print() function and the string concatenation
operation +. The str() function is used to convert the tuple to a string.
Use slicing and concatenation to clear the tuple. Slicing is used to get an empty
tuple, and concatenation is used to combine it with the original tuple. The
resulting tuple is assigned back to the variable test_tup.
Print the resulting tuple using the print() function and the string concatenation
operation +. The str() function is used to convert the tuple to a string.
# initializing tuple
test_tup = (1, 5, 3, 6, 8)
# printing original tuple
print("The original tuple : " + str(test_tup))
Harwinder Singh Sohal
Python(INT-108)
# Clearing a tuple using slicing and concatenation
test_tup = test_tup[0:0] + ()
# print result
print("The tuple after clearing values : " + str(test_tup))
METHOD 5:Using the del keyword
APPROACH:
In this approach, we can simply delete the original tuple using the del keyword, which
clears all the values of the tuple.
ALGORITHM:
1. Assign the tuple to a variable.
2. Use the del keyword to delete the tuple.
3. Print the original tuple and an empty tuple to show that all values have been cleared.
# Input
tup = (1, 5, 3, 6, 8)
# Delete the original tuple using the del keyword
del tup
# Output
print("The original tuple:", (1, 5, 3, 6, 8))
print("The tuple after clearing values:", ())
Sets in Python
A Set in Python programming is an unordered collection data type that is iterable, mutable
and has no duplicate elements.
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a
data structure known as a hash table. Since sets are unordered, we cannot access items using
indexes as we do in lists.
Example of Python Sets
var = {"Geeks", "for", "Geeks"}
type(var)
Type Casting with Python Set method
The Python set() method is used for type casting.
# typecasting list to set
Harwinder Singh Sohal
Python(INT-108)
myset = set(["a", "b", "c"])
print(myset)
# Adding element to the set
myset.add("d")
print(myset)
Check unique and Immutable with Python Set
Python sets cannot have a duplicate value and once it is created we cannot change its value.
# Python program to demonstrate that
# a set cannot have duplicate values
# and we cannot change its items
# a set cannot have duplicate values
myset = {"Geeks", "for", "Geeks"}
print(myset)
# values of a set cannot be changed
myset[1] = "Hello"
print(myset)
Heterogeneous Element with Python Set
Python sets can store heterogeneous elements in it, i.e., a set can store a mixture of string,
integer, boolean, etc datatypes.
# Python example demonstrate that a set
# can store heterogeneous elements
myset = {"Geeks", "for", 10, 52.7, True}
print(myset)
Python Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be
done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the
same after creation.
If no parameters are passed, it returns an empty frozenset.
# Python program to demonstrate differences
# between normal and frozen set
# Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
print("Normal Set")
print(normal_set)
Harwinder Singh Sohal
Python(INT-108)
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
print("\nFrozen Set")
print(frozen_set)
# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")
Internal working of Set
This is based on a data structure known as a hash table. If Multiple values are present at
the same index position, then the value is appended to that index position, to form a Linked
List.
In, Python Sets are implemented using a dictionary with dummy variables, where key
beings the members set with greater optimizations to the time complexity.
Set Implementation:
Sets with Numerous operations on a single HashTable:
Harwinder Singh Sohal
Python(INT-108)
Methods for Sets
Adding elements to Python Sets
Insertion in the set is done through the set.add() function, where an appropriate record value
is created to store in the hash table. Same as checking for an item, i.e., O(1) on average.
However, in worst case it can become O(n).
# A Python program to
# demonstrate adding elements
# in a set
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
print("People:", end = " ")
print(people)
# This will add Daxit
# in the set
people.add("Daxit")
# Adding elements to the
# set using iterator
for i in range(1, 6):
people.add(i)
Harwinder Singh Sohal
Python(INT-108)
print("\nSet after adding element:", end = " ")
print(people)
Union operation on Python Sets
Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at
the same time duplicates are removed. The Time Complexity of this is O(len(s1) +
len(s2)) where s1 and s2 are two sets whose union needs to be done.
# Python Program to
# demonstrate union of
# two sets
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
# Union using union()
# function
population = people.union(vampires)
print("Union using union() function")
print(population)
# Union using "|"
# operator
population = people|dracula
print("\nUnion using '|' operator")
print(population)
Intersection operation on Python Sets
This can be done through intersection() or & operator. Common Elements are selected.
They are similar to iteration over the Hash lists and combining the same values on both the
Table. Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets
whose union needs to be done.
# Python program to
# demonstrate intersection
# of two sets
set1 = set()
Harwinder Singh Sohal
Python(INT-108)
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
print("Intersection using intersection() function")
print(set3)
# Intersection using
# "&" operator
set3 = set1 & set2
print("\nIntersection using '&' operator")
print(set3)
Finding Differences of Sets in Python
To find differences between sets. Similar to finding differences in the linked list. This is
done through difference() or – operator. Time complexity of finding difference s1 – s2 is
O(len(s1))
# Python program to
# demonstrate difference
# of two sets
set1 = set()
set2 = set()
for i in range(5):
set1.add(i)
for i in range(3,9):
set2.add(i)
# Difference of two sets
# using difference() function
set3 = set1.difference(set2)
print(" Difference of two sets using difference() function")
print(set3)
Harwinder Singh Sohal
Python(INT-108)
# Difference of two sets
# using '-' operator
set3 = set1 - set2
print("\nDifference of two sets using '-' operator")
print(set3)
Clearing Python Sets
Set Clear() method empties the whole set inplace.
# Python program to
# demonstrate clearing
# of set
set1 = {1,2,3,4,5,6}
print("Initial set")
print(set1)
# This method will remove
# all the elements of the set
set1.clear()
print("\nSet after using clear() function")
print(set1)
However, there are two major pitfalls in Python sets:
1. The set doesn’t maintain elements in any particular order.
2. Only instances of immutable types can be added to a Python set.
Time complexity of Sets
Operation Average case Worst Case notes
x in s O(1) O(n)
Union s|t O(len(s)+len(t))
replace “min”
O(min(len(s),
Intersection s&t O(len(s) * len(t)) with “max” if t
len(t))
is not a set
Harwinder Singh Sohal
Python(INT-108)
Operation Average case Worst Case notes
Multiple
(n-1)*O(l) where l is
intersection
max(len(s1),..,len(sn))
s1&s2&..&sn
Difference s-t O(len(s))
Operators for Sets
Sets and frozen sets support the following operators:
Operators Notes
key in s containment check
key not in s non-containment check
s1 == s2 s1 is equivalent to s2
s1 != s2 s1 is not equivalent to s2
s1 <= s2 s1 is subset of s2
s1 < s2 s1 is proper subset of s2
s1 >= s2 s1 is superset of s2
s1 > s2 s1 is proper superset of s2
s1 | s2 the union of s1 and s2
s1 & s2 the intersection of s1 and s2
Harwinder Singh Sohal
Python(INT-108)
Operators Notes
s1 – s2 the set of elements in s1 but not s2
s1 ˆ s2 the set of elements in precisely one of s1 or s2
Python – Append Multiple elements in set
Append Multiple Elements in Set in Python
There are various ways by which we can append elements given in a list to a Set in Python.
They are as follows:
Using update() Method
In this method, we will use Python‘s in-built set update() function to get all the elements in
the list aligned with the existing set.
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing original set
print("The original set is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# update() appends element in set
# internally reorders
test_set.update(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
Using | Operator (Pipe Operator)
The pipe operator internally calls the union() function, which can be used to perform the
task of updating the Python set with new elements.
# initializing set
test_set = {6, 4, 2, 7, 9}
Harwinder Singh Sohal
Python(INT-108)
# printing original set
print("The original set is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# | performing task of updating
test_set |= set(up_ele)
# printing result
print("Set after adding elements : " + str(test_set))
Using List Comprehension
Here, we will use the Python list comprehension method to append only those elements in a
set that are not already present in it. Then we use the set() constructor to convert the list to a
Python set.
# initializing set
test_set = {6, 4, 2, 7, 9}
test_list = list(test_set)
# printing original list
print("The original set is : " + str(test_list))
# initializing adding elements
up_ele = [1, 5, 10]
# adding elements to list using list comprehension
test_list += [ele for ele in up_ele if ele not in test_list]
# printing result
Harwinder Singh Sohal
Python(INT-108)
print("Set after adding elements : " + str(set(test_list)))
#This code is contributed by Vinay Pinjala.
Using reduce() Method
This approach uses the reduce() function from the functools module to apply a union
operation between each element of a list and the set, resulting in a new set in Python. The
reduce() function takes a lambda function and the union() function
# import functools
from functools import reduce
# initializing set
test_set = {6, 4, 2, 7, 9}
# printing original list
print("The original list is : " + str(test_set))
# initializing adding elements
up_ele = [1, 5, 10]
# using reduce and union function to append elements to set
result_set = reduce(lambda res, ele: res.union(set([ele])), up_ele, test_set)
# printing result
print("Set after adding elements : " + str(result_set))
Python Set | update()
Python update() function in set adds elements from a set (passed as an argument) to the
set.
Syntax : set1.update(set2)
Here set1 is the set in which set2 will be added.
Parameters : Update() method takes any number of argument. The arguments can be a set,
list, tuples or a dictionary. It automatically converts into a set and adds to the set.
Return value : This method adds set2 to set1 and returns nothing.
Harwinder Singh Sohal
Python(INT-108)
Example of Python set update()
Example 1: Working with Python set update list
# Python program to demonstrate the
# use of update() method
list1 = [1, 2, 3]
list2 = [5, 6, 7]
list3 = [10, 11, 12]
# Lists converted to sets
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
# Print the updated set
print(set1)
# List is passed as an parameter which
# gets automatically converted to a set
set1.update(list3)
print(set1)
Example 2: Python set update element in set
# Python program to demonstrate the
# use of update() method
Harwinder Singh Sohal
Python(INT-108)
list1 = [1, 2, 3, 4]
list2 = [1, 4, 2, 3, 5]
alphabet_set = {'a', 'b', 'c'}
# lists converted to sets
set1 = set(list2)
set2 = set(list1)
# Update method
set1.update(set2)
# Print the updated set
print(set1)
set1.update(alphabet_set)
print(set1)
Example 3: Add elements of the dictionary to Set
number = {1, 2, 3, 4, 5}
num_Dict = {6: 'Six', 7: 'Seven', 8: 'Eight',
9: 'Nine', 10: 'Ten'}
number.update(num_Dict)
print("Updated set: ", number)
Python | Remove items from Set
Harwinder Singh Sohal
Python(INT-108)
Using the pop() method The pop() is an inbuilt method in Python that is used to pop out or
remove the elements one by one from the set. The element that is the smallest in the set is
removed first followed by removing elements in increasing order. In the following
program, the while loop goes onto removing the elements one by one, until the set is
empty.
# Python program to remove elements from set
# Using the pop() method
def Remove(initial_set):
while initial_set:
initial_set.pop()
print(initial_set)
# Driver Code
initial_set = set([12, 10, 13, 15, 8, 9])
Remove(initial_set)
Using discard() method:
Approach:
This approach removes the elements from the set using the discard() method.
Initialize a set my_set with the given elements.
Enter a loop that runs as long as there are elements in the set my_set.
Find the maximum element in the set using the max() function and remove it from the set
using the discard() method.
Print the updated set after each removal.
Exit the loop when the set my_set becomes empty.
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
# remove elements one by one using discard() method
while my_set:
my_set.discard(max(my_set))
print(my_set)
Using remove() method:
Approach:
Initialize set.
Use for loop to iterate length of set times.
Use the remove method on the first element of the set which is retrieved by the
next() method on iter() function.
# initialize the set
my_set = set([12, 10, 13, 15, 8, 9])
Harwinder Singh Sohal
Python(INT-108)
# remove elements one by one using remove() method
for i in range(len(my_set)):
my_set.remove(next(iter(my_set)))
print(my_set)
How to create a Dictionary in Python
Dictionaries are the fundamental data structure in Python and are very important for Python
programmers. They are an unordered collection of data values, used to store data values
like a map. Dictionaries are mutable, which means they can be changed. They offer a time
complexity of O(1) and have been heavily optimized for memory overhead and lookup
speed efficiency.
Create a Dictionary in Python
In Python, a dictionary can be created by placing a sequence of elements within
curly {} braces, separated by a ‘comma’. Let us see a few examples to see how we can
create a dictionary in Python.
Define a Dictionary with Items
In this example, we first declared an empty dictionary D, then added the elements from
the Python list L into the dictionary. The first element of each of the sublists is the key and
the second element is the value. We will store the key-value pair dynamically.
An Overview of Keys and Values
In this example, we will add another element to the existing dictionary in Python. We are
provided with the key and value separately and will add this pair to the dictionary my_dict.
Built-in Dictionary Functions Methods in Python
A dictionary in Python can also be created by the built-in function dict(). In this example,
we first created an empty dictionary using curly braces {}. Then we used the dict() method
and passed a list to it.
How to add values to dictionary in Python
Assign values using unique keys
After defining a dictionary we can index through it using a key and assign a value to it to
make a key-value pair.
Add values to dictionary Using two lists of the same length
This method is used if we have two lists and we want to convert them into a dictionary with
one being key and the other one as corresponding values.
Add values to dictionary Using the in-place merge( |= ) operator.
By using the in place merge operator we can combine two dictionaries. In in place operator,
all elements of one dictionary are added in the other but while using merge original state of
the dictionaries remains the same and a new one is created.
Python del to delete objects
Harwinder Singh Sohal
Python(INT-108)
The del keyword in python is primarily used to delete objects in Python. Since everything
in python represents an object in one way or another, The del keyword can also be used to
delete a list, slice a list, delete a dictionaries, remove key-value pairs from a dictionary,
delete variables, etc.
Syntax: del object_name