Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 22

List Functions

S.No Functions Description and example

1. len() Returns the length of its argument list. It’s a python standard
library function.

l=[1,2,3]

len(l)🡪will return 3

2. list() Returns a list created from the passed argument which


should be a sequence type(string,list, tuple) etc. If no
argument passed it will create an empty list.

a=list(“hello”)

print(a)

output will be:

[‘h’,’e’,’l’,’l’,’o’]

3. index() It returns the index of the first matched item from the list.

Syntax:

list.index(item)

eg:

L=[13,18,11,16,18,14]

L.index(18)

output will be 1

If item is not in the list it raises value Error exception.

4. append() It adds an item to the end of the list.Takes exactly one


element and return no value.

Syntax:

list.append(item)

Eg:

colours=['red','green','yellow']

colours.append('blue')

print(colours)

OUTPUT will be:


['red', 'green', 'yellow', 'blue']

5. extend() It is used for adding multiple elements to a list.

Syntax:

list.extend(list)

It takes list as an argument and appends all of the elements


to the list object

eg:

t1=['a','b','c']

t2=['d','e']

t1.extend(t2)

print(t1)

output will be:


['a', 'b', 'c', 'd', 'e']

6. insert()
● It is also an insertion method for list
● Both append and extend inserts elements at the end.

● insert() inserts elements somewhere in between or any


position of your choice.
Syntax:
list.insert(index,item)
Eg:

t=['a','e','u']

t.insert(2,'i')

print(t)

Output will be:


['a', 'e', 'i', 'u']

7. pop() It is used to remove the item from the list. Takes one optional
argument and returns a value(the item being deleted)

Syntax:

list.pop(index)

● It removes an element from the given position in the


list and return it.

● When no index is specified it removes and returns the


last item in the list.
Eg:

L=[1,2,3,4,5]
val=L.pop(0)

print(val)

print(L)

OUTPUT will be:


1

[2, 3, 4, 5]

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

val=L.pop()

print(val)

print(L)

OUTPUT will be:


5

[1, 2, 3, 4]

8. remove() It removes the first occurrence of given item from the list. It
doesn’t return anything and takes one essential argument.

Syntax:

List.remove(value)

● remove() will report an error if there is no such item in


the list
Eg:

L=['a','e','i','o','u']
L.remove('a')

print(L)

OUTPUT will be
['e', 'i', 'o', 'u']

l=['a','p','b','c','d','p']

l.remove('p')

print(l)

OUTPUT will be
['a', 'b', 'c', 'd', 'p']

9. clear() It removes all the items from the list and the list becomes
empty list after this function. It doesn’t return anything.

Syntax:

list.clear()

l=[1,2,3,4]

l.clear()

print(l)

OUTPUT will be:


[]

10. count() It returns the count of the item that you passed as argument.
If the given item is not in the list it returns zero.
Syntax:

list.count(item)

Eg:

L=[13,18,20,10,18,23]

L.count(18)

OUTPUT will be 2

L.count(28)

OUTPUT will be 0.

11. reverse() It reverses the items of the list.

It doesn’t create a new list.

Syntax:

List.reverse()

Eg:

l=[1,2,3,4]

l.reverse()

print(l)

OUTPUT will be:


[4, 3, 2, 1]

12. sort() It sorts the items of the list by default in increasing order.

It doesn’t create a new list.

Syntax:
list.sort([reverse=False/True])

L=[20,1,16,8,25]

L.sort()

print(L)

OUTPUT will be:


[1, 8, 16, 20, 25]

To sort in descending order you can write:

L=[20,1,16,8,25]

L.sort(reverse=True)

print(L)

OUTPUT will be:


[25, 20, 16, 8, 1]

13. min() The min(),max() and sum() functions take the list sequence
and return the minimum element, maximum element and
max()
the sum of elements of the list respectively.
sum()
Syntax:

min(list)

max(list)

sum(list)

Eg:

L=[20,1,16,8,25]

print(min(L))
print(max(L))

print(sum(L))

OUTPUT will be:


1

25

70

Tuple Functions
1. len() Eg: t=(1,2,3,4)
It returns the length of the tuple. ie counts print(len(t))
the no:of elements in the tuple.
Output will be:
syntax:
4
len(tuple)
2. max() Eg:
It returns the element from tuple with t=(2,90,45,8)
maximum value.
print(max(t))
Values in the tuple must be of same type.
Output will be:
Syntax: 90

max(tuple)

3. min() Eg:
It returns the element from tuple with t=(2,90,45,8)
minimum value.
print(min(t))
Values in the tuple must be of same type. Output will be:
Syntax: 2
min(tuple)
4. sum() Eg:
It takes tuple as parameter and returns the t=(51,2,91,6)
sum of elements of the tuple.
sum(t)
Output is
150
5. index() Eg:
It returns the index of an existing element of t=(1,2,3,4)
a tuple.
t.index(3)
Syntax:
Output will be:
tuple.index(item)
2
6. count() Eg:
It returns the count of a element in a given t=(1,2,3,1,2,4,1,2,3)
sequence.
t.count(2)
Syntax:
Output will be:
tuple.count(element)
3
7. sorted() Eg:
It takes name of the argument and returns a t=(51,2,91,6)
new sorted list with sorted elements in it.
t1=sorted(t)
Syntax:
print(t1)
sorted(tuple,[reverse=False])
Output will be:
This sorts is ascending order. [2, 6, 51, 91]

If needs to be sorted in descending order t=(51,2,91,6)


use:
sorted(tuple,reverse=True) t1=sorted(t,reverse=True)
print(t1)
Output will be:
[91, 51, 6, 2]

8. tuple() Eg:
It is used to create tuples from different type Empty tuple
of values.
t=()
Syntax:
print(t)
tuple(Sequence)
Output will be:
()
t=tuple("abc")
print(t)
Output will be:
('a', 'b', 'c')

● Dictionary Functions and methods


1. len() Eg:
● It is used to get the length d={1:20,2:30,3:40,4:50}
of the dictionary. print(len(d))
● To count the key: value Output will be:
pair you can use the len() 4
function
Syntax:
len(dictionary)
2. get() Eg:
● It is used to get the item d={'name':"abhay","age":18,"class":1
with the given key 2}
● If key is not present, it d.get("age")
gives error. Output:
Syntax: 18
Dictionary.get(key) It will return the value for given key.
3. items() d={1:10,2:20,3:30,4:40}
● It returns all of the items d.items()
in the dictionary as a Output:
dict_items([(1, 10), (2, 20), (3,
sequence of (key,value) 30), (4, 40)])
tuples. II.
Syntax: d={1:10,2:20,3:30,4:40}
Dictionary.items() l=d.items()
for i in l:
print(i)
Output:
(1, 10)
(2, 20)
(3, 30)
(4, 40)
III.
d={1:10,2:20,3:30,4:40}
l=d.items()
for i,j in l:
print(i,j)
Output:
1 10
2 20
3 30
4 40

4. keys() Eg:
● It returns all the keys in d={1:10,2:20,3:30,4:40}
the dictionary as a d.keys()
sequence of keys. Output will be:
dict_keys([1, 2, 3, 4])
syntax:
dictionary.keys()
5. values() Eg:
● It returns all the values in d={1:10,2:20,3:30,4:40}
the dictionary as a d.values()
sequence of keys. Output will be:
syntax: dict_values([10, 20, 30, 40])

dictionary.values()
6. update() Eg:
● This merges key:value d={1:10,2:20,3:30}
pairs from the new d1={4:40,5:50}
dictionary in to the d.update(d1)
original dictionary adding print(d)
or replacing as needed. print(d1)
● The items in the new Output will be:
{1: 10, 2: 20, 3: 30, 4: 40, 5:
dictionary are added to 50}
the old one and override {4: 40, 5: 50}

any items already there


with the same keys.
Syntax:
dictionary.update(other
dictionary)
7. fromkeys() Eg:
● fromkeys() is used to nd=dict.fromkeys([2,4,6,8],100)
create a new dictionary print(nd)
from a sequence Output:
{2: 100, 4: 100, 6: 100, 8: 100}
containing all the keys and
a common value, which nd=dict.fromkeys((2,4,6,8))
will be assigned to all the print(nd)
keys. Output will be:
Syntax: {2: None, 4: None, 6: None, 8:
None}
dict.fromkeys(key In [ ]:
sequence,value)
Where,
Key sequence 🡪 is a
python sequence
containing the keys for the
new dictionary.
Value🡪 is the common
value that will be assigned
to all the keys.
8. setdefault() Eg:
● This method inserts a new marks={1:45,2:67,3:90,4:87}
key:value pair. marks.setdefault(5,89)
● It works as follows: Output:
89
● If given key is not already marks={1:45,2:67,3:90,4:87}
present in the marks.setdefault(4,89)
dictionary ,it will add the Output will be:
specified new key:value 87
pair to the dictionary and
returns it
● If the given key is already
present in the dictionary,
the dictionary will not be
updated but the current
value associated to the
specified key is returned.
pop() Eg:
• It removes and returns the d={1:10,2:20,3:30,4:40}
dictionary element associated to d.pop(2)
passed key. Output will be:
• It raises an error if 20
mentioned key is not present in Remember pop() function delete the
the dictionary.However you can key:value pair for mentioned key and
give your own personalized also returns the value it deleted.
message when a key is not there d={1:10,2:20,3:30,4:40}
in the dictionary d.pop(5,"not found")
Syntax: Output will be:
dictionary.pop(key) 'not found'

9. popitem() Eg: d={1:10,2:20,3:30,4:40}


● It returns the items which d.popitem()
was the last item entered Output will be:
(4, 40)
in the dictionary.
● It returns the deleted
key:value pair in the form
of a tuple.
● If dictionary is empty
calling popitem() raises an
error.
syntax:
dictionary.popitem()
10 del Eg:
. ● It is statement used to d={1:10,2:20,3:30,4:40}
delete a key:value pair del d[2]
from a dictionary print(d)
● It will not return the value output will be:
{1: 10, 3: 30, 4: 40}
it has deleted.
Syntax:
del dictionary[key]
11 clear() Eg:
. ● This removes all items d={1:10,2:20,3:30,4:40}
from the dictionary and d.clear()
dictionary becomes empty print(d)
dictionary post this output will be:
{}
method.
syntax:
dictionary.clear()
12 copy() eg:
. ● it creates a shallow copy names={1:"abhay",2:"athira",3:"chitr
of a dictionary. a"}
● It returns a shallow copy names1=names.copy()
of the dictionary print(names1)
output will be:
syntax: {1: 'abhay', 2: 'athira', 3:
'chitra'}
dictionary.copy()
names={1:"abhay",2:"athira",3:"chitr
a"}
names1=names.copy()
names1[4]="dany"
print(names1)
print(names)
Output will be:
{1: 'abhay', 2: 'athira', 3:
'chitra', 4: 'dany'}
{1: 'abhay', 2: 'athira', 3:
'chitra'}
names={1:[1,2],2:[1,2,3]}
names1=names.copy()
names1[2].append(4)
print(names1)
print(names)
output will be:
{1: [1, 2], 2: [1, 2, 3, 4]}
{1: [1, 2], 2: [1, 2, 3, 4]}

13 sorted() Eg:
. ● It considers only the keys d={90:"abc",45:"def",2:"pqr",92:"hij"
of the dictionary for }
sorting and returns a d1=sorted(d)
sorted list of the print(d1)
dictionary keys output:
[2, 45, 90, 92]
Syntax: d={90:"abc",45:"def",2:"pqr",92:"hij"
sorted(dictionary,reverse=Fal }
se) d1=sorted(d,reverse=True)
if reverse argument is true, print(d1)
then it returns tge keys of output will be:
the dictionary sorted in [92, 90, 45, 2]

descending order.
● it returns the result always
in a list.
● all keys must be of same
type for this function to
work.
14 max(),min() and sum() eg:
. ● dictionary key must be of d={1:10,2:90,80:50,75:9}
homogenous type. print(min(d))
syntax: print(max(d))
max(dictionary) print(sum(d))
min(dictionary) Output will be:
1
sum(dictionary) 80
158
● sum() can only work with
dictionaries having keys
which are addition
compatable.

● String Built in Functions

1. len() eg:
Returns the length of its argument string len(“hello”)
Syntax: will return 5
len(string) (Total no:of characters in the
string)

2. capitalize() Eg:
It returns a copy of the string with its first ‘i love my India’.capitalize()
character capitalized
will return
Syntax:
I love my India
string.capitalize()

3. lower() Eg:
It returns a copy of the string converted to “HELLO”.lower()
lowercase
‘hello’
Syntax:
“hi”.lower()
string.lower()
‘hi’

4. upper() eg:
It returns a copy of the string converted to ‘hello’.upper()
uppercase
‘HELLO’
Syntax:
“HI”.upper()
string.upper() “HI”

5. count() Eg:
It returns the number of occurrences of the ‘abracadabra’.count(‘ab’)
substring sub in string[or string[start: end] if these
It counts the no: of
arguments are given.
occurrences of ‘ab’ in the
Syntax: whole string. So it returns 2.
string.count(sub[,start[,end]])

6. find() s="hi hello there hi hello"


It returns the lowest index in the string where the s.find("hello")
substring sub is found within the slice range of
Returns 3
start and end. Returns -1 if sub is not found.
s="hi hello there hi hello"
string.find(sub[,start[,end]])
s.find("hello",10,30)
Returns 18

7. index() Eg:

● It returns the lowest index where the s='abcrabdcab'

specified substring is found. If substring is s.index('ab')


not found then value error is raised.
Returns 0
● It is same as find but find() returns -1 if the s='abcrabdcab'
sub is not found, but index() raises a value
s.index('ab',2,4)
error.
Returns:
string.index(sub[,start[,end]])
ValueError: substring not
found

8. isalnum() Eg:
It returns True if characters in the string are s=’abc123’
alphanumeric (alphabets or numbers) and there is s.isalnum() returns True
at least one character, False otherwise.
s=’123’
Syntax:
s.isalnum() returns True
string.isalnum()
s=’ ‘
s.isalnum() returns False

9. isalpha() Eg:
It returns True if all characters in the string are s=’abc123’
alphabetic and there is at least one character,
s.isalpha() returns False
False otherwise.
s=’hello’
Syntax:
s.isalpha() returns True
string.isalpha()

10. isdigit() Eg:


It returns True if all the characters in the string are s=’abc123’
digits there is at least one character, False
s.isdigit() returns False
otherwise.
s=’123’
string.isdigit()
s.isdigit() returns True

11. islower() Eg:


It returns True if all cased characters in the string s=’hello’
are lowercase. There must be at least one cased
s.islower() returns True.
character. It returns False otherwise.
s=’HI’
Syntax:
s.islower() returns False
string.islower()
s=’Golden’
s.islower() returns False

12. isupper() Eg:


It returns True if all cased characters in the string s=’hello’
are uppercase. There must be at least one cased
s.isupper() returns False.
character. It returns False otherwise.
s=’HI’
Syntax:
s.isupper() returns True.
string.isupper()
s=’Golden’
s.isupper() returns False.
s=’Golden’
s1=”A123”
s.isupper() returns True

13. title() Eg:


It returns a title cased version of the string where ‘python is fun’.title()
all words start with uppercase characters and all
returns
remaining letters are in lowercase.
Python Is Fun
Syntax:
string.title()

14. istitle() Eg:


It returns True if the string has the title case, (ie ‘Computer Science’.istitle()
the first letter of each word in uppercase while
Returns True
rest in lowercase), False otherwise.
Syntax:
string.istitle()
15. isspace() Eg:
It returns True if there are only whitespace s=” “
characters in the string. There must be at least one
s.isspace() Returns True
character. It returns False otherwise.
s=””
Syntax:
s.isspace() returns False
string.isspace()

16. lstrip() Eg:


Returns a copy of the string with leading s=” python “.lstrip()
whitespaces removed ie whitespaces from the returns “python “
leftmost end are removed.
syntax:
string.lstrip()

17. rstrip() Eg:


Returns a copy of the string with trailing s=” python “.rstrip()
whitespaces removed ie, whitespaces from the returns “ python“
rightmost end are removed.
syntax:
string.rstrip()

18. strip() Eg:


Returns a copy of the string with leading and s=” python “.strip()
trailing whitespaces removed ie whitespaces from
returns “python”
the leftmost end and rightmost end are removed.
syntax:
string.strip()

19. startswith() Eg:


Returns true if the string starts with the substring “abccd”.startswith(“ab”)
sub, otherwise returns False.
returns True
Syntax:
string.startswith()

20. endswith() Eg:


Returns true if the string ends with the substring “abcd”.endswith(‘d’)
sub, otherwise returns False.
Returns True
Syntax:
string.endswith()

21. replace() Eg:


It returns a copy of the string with all occurances “I work for
of substring old replaced by new string. It is used you”.replace(“work”,”care”)
as per the syntax:
returns:
string.replace(old,new)
“I care for you”

22. join() Eg:


“**”.join(“Hello”)
● It joins a string or character after each
member of the string iterator. Returns

Syntax: “H**e**l**l**o”

string.join(String iterable)

● If the string based iterator is a list or tuple,


then the given string/character is joined “$$”.join([“Hi”,”hello”])
with each member of the list or tuple.(Tuple ‘hi$$hello’
and list must have all members as string,
otherwise python raises error)

23. spilt() Eg:


“I Love Python”.split()

● It splits a string based on given string or [‘I’,’Love’,’Python’]


character and returns a list containing split
strings as members.
Syntax:
string.split(string/char)

● If you don’t provide any argument, by


default whitespace will be taken as
“I Love Python”.split(‘o’)
separator
[‘I L’,’ve Pyth’,’n’]
● If you provide an argument, the given string
is divided in to parts considering the given
string/char as separator and separator
character is not included in the split strings.
24. partition() Eg:
It splits the string at the first occurrence of txt=”I enjoy working with
separator, and returns a tuple containing three python”
items.
x=txt.partition(“working”)
● The part before separator print(x)
Returns:
● The separator itself
(“I enjoy”,”working”,”with
● The part after separator python”)

Syntax:
string.partition(separator/string)

You might also like