Q) what is Lists?
Lists are used to store multiple items in a single variable.
Lists are created using square brackets. A list is created in Python by placing
items inside [], separated by commas
List items are ordered, changeable, and allow duplicate values.
List items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered:
When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
If you add new items to a list, the new items will be placed at the end of the
list.
Changeable:
The list is changeable, meaning that we can change, add, and remove items in
a list after it has been created.
Allow Duplicates:
Since lists are indexed, lists can have items with the same value.
Syntax:listname=[val1,val2,…………,valN]
Example:
# A list with 3 integers
numbers = [1, 2, 5]
print(numbers)
# Output: [1, 2, 5]
……………………………. End…………..
Q) List Operations ?
The concatenation (+) and repetition (*) operators work in the same way as
they were working with the strings. The different operations of list are
1. Repetition
2. Concatenation
3. Length
4. Iteration
5. Membership
Let's see how the list responds to various operators.
1. Repetition:
The repetition operator enables the list elements to be repeated multiple
times.
Example:
# repetition of list
# declaring the list
list1 = [12, 14, 16, 18, 20]
# repetition operator *
l = list1 * 2
print(l)
Output:
[12, 14, 16, 18, 20, 12, 14, 16, 18, 20]
2. Concatenation:
It concatenates the list mentioned on either side of the operator.
Example:
# concatenation of two lists
# declaring the lists
list1 = [12, 14, 16, 18, 20]
list2 = [9, 10, 32, 54, 86]
# concatenation operator +
l = list1 + list2
print(l)
Output:
[12, 14, 16, 18, 20, 9, 10, 32, 54, 86]
3. Length:
It is used to get the length of the list
Example:
# size of the list
# declaring the list
list1 = [12, 14, 16, 18, 20, 23, 27, 39, 40]
# finding length of the list
len(list1)
Output:
4. Iteration:
The for loop is used to iterate over the list elements.
Example:
# iteration of the list
# declaring the list
list1 = [12, 14, 16, 39, 40]
# iterating
for i in list1:
print(i)
Output:
12
14
16
39
40
5. Membership:
It returns true if a particular item exists in a particular list otherwise false.
Example:
# membership of the list
# declaring the list
list1 = [100, 200, 300, 400, 500]
# true will be printed if value exists
# and false if not
print(600 in list1)
print(700 in list1)
print(1040 in list1)
print(300 in list1)
print(100 in list1)
print(500 in list1)
Output:
False
False
False
True
True
True
…………………… end………………
Q) slicing in list ?
The format for list slicing is [start:stop:step].
start is the index of the list where slicing starts.
stop is the index of the list where slicing ends.
step allows you to select nth item within the range start to stop.
Example:
Get all the Items from One Position to Another Position
my_list = [1, 2, 3, 4, 5]
print(my_list[2:4])
Output
[3, 4]
List slicing works similar to Python slice() function.
The slice() function returns a slice object that is used to slice any sequence
(string, tuple, list, range, or bytes).
Syntax
slice(start, end, step)
Parameter Values
Parameter Description
Start Optional. An integer number specifying at which position to start
the slicing. Default is 0
End An integer number specifying at which position to end the slicing
Step Optional. An integer number specifying the step of the slicing.
Default is 1
Example
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(a[x])
output:
( ‘d’, ’e’ )
……………………end ……………..
Q ) List Methods ?
1)append( ): Adds an element at the end of the list
Syntax
[Link](elmnt)
Parameter Values
Parameter Description
Elmnt Required. An element of any type (string, number, object etc.)
Example:
fruits = ["apple", "banana", "cherry"]
[Link]("orange")
print(fruits)
Output:
['apple', 'banana', 'cherry', 'orange']
2)clear( ) : Removes all the elements from the list
Syntax
[Link]()
Parameter Values
No parameters
Example:
fruits = ["apple", "banana", "cherry"]
[Link]()
print(fruits)
output: [ ]
3)copy ( ) : Returns a copy of the list .
Syntax
[Link]()
Parameter Values
No parameters
Example:
fruits = ["apple", "banana", "cherry"]
x = [Link]()
print(x)
output: ['apple', 'banana', 'cherry']
4)count( ) : Returns the number of elements with the specified value
Syntax
[Link](value)
Parameter Values
Parameter Description
Value Required. Any type (string, number, list, tuple, etc.). The
value to search for.
Example:
fruits = ["apple", "banana", "cherry"]
x = [Link]("cherry")
print(x)
output: 1
5) index ( ) : Returns the index of the first element with the specified value
Syntax
[Link](elmnt)
Parameter Values
Parameter Description
Elmnt Required. Any type (string, number, list, etc.). The element to
search for
Example:
fruits = [4, 55, 64, 32, 16, 32]
x = [Link](32)
print(x)
output: 3
6) insert ( ) : Adds an element at the specified position
Syntax
[Link](pos, elmnt)
Parameter Values
Parameter Description
Pos Required. A number specifying in which position to
insert the value
Elmnt Required. An element of any type (string, number, object
etc.)
Example:
fruits = ['apple', 'banana', 'cherry']
[Link](1, "orange")
print(fruits)
output: ['apple', 'orange', 'banana', 'cherry']
7) pop( ) : Removes the element at the specified position
Syntax
[Link](pos)
Parameter Values
Parameter Description
Pos Optional. A number specifying the position of the element you
want to remove, default value is -1, which returns the last item
Example:
fruits = ['apple', 'banana', 'cherry']
[Link](1)
print(fruits)
output: ['apple', 'cherry']
………………….. end ………………
Q) what isTuple ?
Tuples are used to store multiple items in a single variable.
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuples are written with round brackets.
Tuple items are indexed, the first item has index [0], the second item has
index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined
order, and that order will not change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value
Syntax: tuplename=(val1,val2,……..,valN)
Example:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
output: ('apple', 'banana', 'cherry', 'apple', 'cherry')
……………….. end ……………………
Q) tuple methods ?
python has two built-in methods that you can use on tuples.
1) count( ) : Returns the number of times a specified value occurs in a tuple
Syntax
[Link](value)
Parameter Values
Parameter Description
value Required. The item to search for
Example:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](5)
print(x)
output: 2
2) index( ) : Searches the tuple for a specified value and returns the position of
where it was found
Syntax
[Link](value)
Parameter Values
Parameter Description
value Required. The item to search for
Example:
thistuple = (1, 3, 7, 8, 7, 5, 4, 6, 8, 5)
x = [Link](8)
print(x)
output: 3
………………………. End ……………………….
Q)what is set ?
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*, and unindexed.
Sets are written with curly brackets.
Example:
thisset = {"apple", "banana", "cherry"}
print(thisset)
output:
{'banana', 'apple', 'cherry'}
…………………………. End ……………
Q) set methods ?
1) add ( ) : The add() method adds an element to the set.
Syntax
[Link](elmnt)
Parameter Values
Parameter Description
elmnt Required. The element to add to the set
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("apple")
print(thisset)
output:
{'banana', 'cherry', 'apple'}
2. clear ( ) : The clear() method removes all elements in a set.
Syntax
[Link]()
Parameter Values
No parameters
Example:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)
output: set()
[Link] ( ) : The copy() method copies the set.
Syntax
[Link]()
Parameter Values
No parameters
Example:
fruits = {"apple", "banana", "cherry"}
x = [Link]()
print(x)
output: {'apple', 'banana', 'cherry'}
4. update ( ) : The update() method updates the current set, by adding items
from another set (or any other iterable).
If an item is present in both sets, only one appearance of this item will be
present in the updated set.
Syntax
[Link](set)
Parameter Values
Parameter Description
set Required. The iterable insert into the current set
Example:
x = {"apple", "banana", "cherry"}
y = {"google", "microsoft", "apple"}
[Link](y)
print(x)
output: {'apple', 'google', 'microsoft', 'banana', 'cherry'}
[Link]( ) :
The discard() method removes the specified item from the set.
This method is different from the remove() method, because
the remove() method will raise an error if the specified item does not exist,
and the discard() method will not.
Syntax
[Link](value)
Parameter Values
Parameter Description
value Required. The item to search for, and remove
Example:
thisset = {"apple", "banana", "cherry"}
[Link]("banana")
print(thisset)❮pffd; Set Methods
❮ Se555t Methods
Output: {'apple', 'cherry'}
[Link]( ) :
The pop() method removes a random item from the set.
This method returns the removed item.
Syntax
[Link]()
Parameter Values
No parameter values.
Example:
fruits = {"apple", "banana", "cherry"}
[Link]()
print(fruits)
output: {'banana', 'apple'}
……………………………. End …………….
Q) what is sequence ?
Sequences are containers with items stored in a deterministic ordering. Each
sequence data type comes with its unique capabilities.
……………….. end ………….
Q) Types of Sequences in Python ?
Python sequences are of six types, namely:
1. Strings
2. Lists
3. Tuples
4. Bytes Sequences
5. Bytes Arrays
6. range() objects
Strings in Python
In python, the string is a sequence of Unicode characters written inside a
single or double-quote. Python does not have any char type as in other
languages (C, C++), therefore, a single character inside the quotes will be of
type str only.
1. To declare an empty string, use str() or it can be defined using empty
string inside quotes.
Example of Empty String in Python
name = "PythonGeeks"
print(name)
Output
PythonGeeks
Lists in Python
Lists are a single storage unit to store multiple data items together. It’s a
mutable data structure, therefore, once declared, it can still be altered.
A list can hold strings, numbers, lists, tuples, dictionaries, etc.
1. To declare a list, either use list() or square brackets [], containing comma-
separated values.
Example of Lists in Python
list_1 = ["PythonGeeks", "Sequences", "Tutorial"] # [all string list]
print(f'List 1: {list_1}')
list_2 = list() # [empty list]
print(f'List 2: {list_2}')
list_3 = [2021, ['hello', 2020], 2.0] # [integer, list, float]
print(f'List 3: {list_3}')
list_4 = [{'language': 'Python'}, (1,2)] # [dictionary, tuple]
print(f'List 4: {list_4}')
Output
List 1: [‘PythonGeeks’, ‘Sequences’, ‘Tutorial’]
List 2: []
List 3: [2021, [‘hello’, 2020], 2.0]
List 4: [{‘language’: ‘Python’}, (1, 2)]
Tuples in Python
Just like Lists, Tuples can store multiple data items of different data types. The
only difference is that they are immutable and are stored inside the
parenthesis ().
1. To declare a tuple, either use tuple() or parenthesis, containing comma-
separated values.
Example of Tuple in Python:
tuple_1 = ("PythonGeeks", "Sequences", "Tutorial") # [all string tuple]
print(f'tuple 1: {tuple_1}')
tuple_2 = tuple() # [empty tuple]
print(f'tuple 2: {tuple_2}')
tuple_3 = [2021, ('hello', 2020), 2.0] # [integer, tuple, float]
print(f'tuple 3: {tuple_3}')
tuple_4 = [{'language': 'Python'}, [1,2]] # [dictionary, list]
print(f'tuple 4: {tuple_4}')
Output:
tuple 1: (‘PythonGeeks’, ‘Sequences’, ‘Tutorial’)
tuple 2: ()
tuple 3: [2021, (‘hello’, 2020), 2.0]
tuple 4: [{‘language’: ‘Python’}, [1, 2]]
Byte Sequences in Python
The bytes() function returns an immutable bytes sequence in between
quotes, preceded by a ‘B’ or ‘b’.
1. To declare an empty bytes object, use bytes(size), where size is the number
of empty bytes we want to generate.
Example of Byte Sequences in Python:
size = 10
b = bytes(size)
print(b)
Output:
b’\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00′
range() object in Python
It returns a sequence of integers in the specified range. By default, it starts
the sequence from 0 (if not specified).
Code:
sequence = range(10)
print(sequence)
Output:
range(0,10)
…………………. End …………
Q) Operations on Sequences in Python ?
We now know the types of sequences, but now, it’s time to see what all
operations can we perform on them. Here, we will focus on the most
commonly used operations.
1. Concatenation Operator in Python
(+) operator is used to join two sequences of the same type.
Code:
print(["Python"] + ["Geeks"])
Output:
[“Python”, “Geeks”]
2. Repeat Operator in Python
(*) operator repeats a sequence specified number of times.
Code:
print(("PythonGeeks", 1) * 2)
Output:
(‘PythonGeeks’, 1, ‘PythonGeeks’, 1)
3. Membership Operator in Python
These are used to check whether a value is present in a sequence or not using
the “in” and “not in” operators.
Code:
dict = {
"lang" : "Python",
"platform": "PythonGeeks"
}
print("lang" in dict)
print("code" not in dict)
Output:
True
True
4. Slicing Operator in Python
[:] operator returns a part of the sequence between a given range.
Code:
list_1 = [3,2,5,6,7]
print(list_1[:5])
print(list_1[2:4])
print(list_1[-1:])
Output:
[3, 2, 5, 6, 7]
[5, 6]
[7]
……………… end ………….
Q)Python Sequence Functions and Methods ?
1. len(sequence) : Returns length of a sequence.
2. index(index): Returns index of the first occurrence of an element in a
sequence.
3. min(sequence): Returns the minimum value of a sequence.
4. max(sequence): Returns maximum value of a sequence.
5. count(): Returns the count of a number of occurrences of an element in a
sequence.
6. append(value): Adds the value at the end of the sequence.
7. clear(): Clears all the contents of the sequence.
8. insert(value, index): Inserts the value at the index “index” of the
sequence.
9. pop(index): Returns and deletes elements at index “index”. By default, the
last element is deleted from the sequence.
10. remove(value): Removes the first occurrence of value from the
sequence.
11. reverse(): Reverse the sequence
Example of Sequence Function in Python
test = [2, 4, 6, 8, 10, 10]
print(len(test))
print([Link](6))
print(min(test))
print(max(test))
print([Link](10))
[Link](11)
print(test)
[Link]()
print(test)
test = [2, 4, 6, 8, 10, 10]
[Link](9,4)
print(test)
print([Link]())
[Link](10)
print(test)
[Link]()
print(test)
output:
6
2
2
10
2
[2, 4, 6, 8, 10, 10, 11]
[]
[2, 4, 6, 8, 10, 10, 4]
4
[2, 4, 6, 8, 10]
[10, 8, 6, 4, 2]
………………….. end ………….
Q)what is dictionaries ?
o Python Dictionary is used to store the data in a key-value pair format.
o It is the mutable data-structure.
o The elements Keys and values is employed to create the dictionary.
o Keys must consist of just one element.
o Value can be any type such as list, tuple, integer, etc.
Ordered or Unordered?
o As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier,
dictionaries are unordered.
o When we say that dictionaries are ordered, it means that the items have
a defined order, and that order will not change.
o Unordered means that the items does not have a defined order, you
cannot refer to an item by using an index.
Changeable
o Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.
Duplicates Not Allowed
o Dictionaries cannot have two items with the same key:
Syntax:
Dictionaryname= {
key:value,
Key:value,
……………….
………………
}
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
print(thisdict)
output:
{'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
…………… end ………………….
Q) dictionary methods ?
1) copy ( ) : Returns a copy of the dictionary
Syntax
[Link]()
Parameter Values
No parameters
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = [Link]()
print(x)
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
2)clear ( ) : Removes all the elements from the dictionary
Syntax
[Link]()
Parameter Values
No parameters
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
[Link]()
print(car)
output: {}
3. get ( ) : Returns the value of the specified key
Syntax
[Link](keyname, value)
Parameter Values
Parameter Description
keyname Required. The keyname of the item you want to return the
value from
value Optional. A value to return if the specified key does not exist.
Default value None
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = [Link]("model")
print(x)
output: Mustang
4. keys ( ) : Returns a list containing the dictionary's keys
Syntax
[Link]()
Parameter Values
No parameters
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
x = [Link]()
print(x)
output: dict_keys(['brand', 'model', 'year'])
5. values( ) : Returns a list of all the values in the dictionary
Syntax
[Link]()
Parameter Values
No parameters
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = [Link]()
print(x)
output: dict_values(['Ford', 'Mustang', 1964])
[Link] ( ) : Updates the dictionary with the specified key-value pairs
Syntax
[Link](iterable)
Parameter Values
Parameter Description
iterable A dictionary or an iterable object with key value pairs, that will
be inserted to the dictionary
Example:
Syntax
[Link](iterable)
Parameter Values
Parameter Description
iterable A dictionary or an iterable object with key value pairs, that
will be inserted to the dictionary
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
[Link]({"color": "White"})
print(car)
output: {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'White'}
[Link]( ) : The pop() method removes the specified item from the dictionary.
Syntax
[Link](keyname, defaultvalue)
Parameter Values
Parameter Description
keyname Required. The keyname of the item you want to remove
defaultvalue Optional. A value to return if the specified key do not exist.
If this parameter is not specified, and the no item with the
specified key is found, an error is raised
Example:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
[Link]("model")
print(car)
output : {'brand': 'Ford', 'year': 1964}
…………………. End ………….
Q) comprehensions ?
Comprehensions in Python provide us with a short and concise way to
construct new sequences (such as lists, set, dictionary etc.) using sequences
which have been already defined. Python supports the following 4 types of
comprehensions:
List Comprehensions
Dictionary Comprehensions
Set Comprehensions
Generator Comprehensions
List Comprehensions:
List Comprehensions provide an elegant way to create new lists. The
following is the basic structure of a list comprehension:
output_list = [output_exp for var in input_list if (var satisfies this condition)]
Note that list comprehension may or may not contain an if condition. List
comprehensions can contain multiple for (nested list comprehensions).
Example #1: Suppose we want to create an output list which contains only
the even numbers which are present in the input list. Let’s see how to do this
using for loops and list comprehension and decide which method suits better.
# Constructing output list WITHOUT
# Using List comprehensions
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_list = []
# Using loop for constructing output list
for var in input_list:
if var % 2 == 0:
output_list.append(var)
print("Output List using for loop:", output_list)
Output:
Output List using for loop: [2, 4, 4, 6]
# Using List comprehensions
# for constructing output list
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
list_using_comp = [var for var in input_list if var % 2 == 0]
print("Output List using list comprehensions:",
list_using_comp)
Output:
Output List using list comprehensions: [2, 4, 4, 6]
Example #2: Suppose we want to create an output list which contains squares of all the
numbers from 1 to 9. Let’s see how to do this using for loops and list comprehension.
# Constructing output list using for loop
output_list = []
for var in range(1, 10):
output_list.append(var ** 2)
print("Output List using for loop:", output_list)
Output:
Output List using for loop: [1, 4, 9, 16, 25, 36, 49, 64, 81]
# Constructing output list
# using list comprehension
list_using_comp = [var**2 for var in range(1, 10)]
print("Output List using list comprehension:",
list_using_comp)
Output:
Output List using list comprehension: [1, 4, 9, 16, 25, 36, 49, 64, 81]
Dictionary Comprehensions:
Extending the idea of list comprehensions, we can also create a dictionary
using dictionary comprehensions. The basic structure of a dictionary
comprehension looks like below.
output_dict = {key:value for (key, value) in iterable if (key, value satisfy this
condition)}
Example #1: Suppose we want to create an output dictionary which contains only the odd
numbers that are present in the input list as keys and their cubes as values. Let’s see how to do
this using for loops and dictionary comprehension.
input_list = [1, 2, 3, 4, 5, 6, 7]
output_dict = {}
# Using loop for constructing output dictionary
for var in input_list:
if var % 2 != 0:
output_dict[var] = var**3
print("Output Dictionary using for loop:",
output_dict )
Output:
Output Dictionary using for loop: {1: 1, 3: 27, 5: 125, 7: 343}
# Using Dictionary comprehensions
# for constructing output dictionary
input_list = [1,2,3,4,5,6,7]
dict_using_comp = {var:var ** 3 for var in input_list if var % 2 != 0}
print("Output Dictionary using dictionary comprehensions:",
dict_using_comp)
Output:
Output Dictionary using dictionary comprehensions: {1: 1, 3: 27, 5: 125, 7:
343}
Example #2: Given two lists containing the names of states and their corresponding capitals,
construct a dictionary which maps the states with their respective capitals. Let’s see how to do
this using for loops and dictionary comprehension.
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
output_dict = {}
# Using loop for constructing output dictionary
for (key, value) in zip(state, capital):
output_dict[key] = value
print("Output Dictionary using for loop:",
output_dict)
Output:
Output Dictionary using for loop: {'Gujarat': 'Gandhinagar',
'Maharashtra': 'Mumbai',
'Rajasthan': 'Jaipur'}
# Using Dictionary comprehensions
# for constructing output dictionary
state = ['Gujarat', 'Maharashtra', 'Rajasthan']
capital = ['Gandhinagar', 'Mumbai', 'Jaipur']
dict_using_comp = {key:value for (key, value) in zip(state, capital)}
print("Output Dictionary using dictionary comprehensions:",
dict_using_comp)
Output:
Output Dictionary using dictionary comprehensions: {'Rajasthan': 'Jaipur',
'Maharashtra': 'Mumbai',
'Gujarat': 'Gandhinagar'}
Set Comprehensions:
Set comprehensions are pretty similar to list comprehensions. The only
difference between them is that set comprehensions use curly brackets { }.
Let’s look at the following example to understand set comprehensions.
Example #1 : Suppose we want to create an output set which contains only the even numbers
that are present in the input list. Note that set will discard all the duplicate values. Let’s see how
we can do this using for loops and set comprehension.
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
output_set = set()
# Using loop for constructing output set
for var in input_list:
if var % 2 == 0:
output_set.add(var)
print("Output Set using for loop:", output_set)
Output:
Output Set using for loop: {2, 4, 6}
# Using Set comprehensions
# for constructing output set
input_list = [1, 2, 3, 4, 4, 5, 6, 6, 6, 7, 7]
set_using_comp = {var for var in input_list if var % 2 == 0}
print("Output Set using set comprehensions:",
set_using_comp)
Output:
Output Set using set comprehensions: {2, 4, 6}
Generator Comprehensions:
Generator Comprehensions are very similar to list comprehensions. One difference between
them is that generator comprehensions use circular brackets whereas list comprehensions use
square brackets. The major difference between them is that generators don’t allocate memory for
the whole list. Instead, they generate each value one by one which is why they are memory
efficient. Let’s look at the following example to understand generator comprehension:
input_list = [1, 2, 3, 4, 4, 5, 6, 7, 7]
output_gen = (var for var in input_list if var % 2 == 0)
print("Output values using generator comprehensions:", end = ' ')
for var in output_gen:
print(var, end = ' ')
Output:
Output values using generator comprehensions: 2 4 4 6
………………….. end ………….