List Methods
List [] is a collection of elements that is ordered and mutable. they can contain elements of different
data types, including integers, floats, strings, and even other lists.
Lists are mutable, meaning that elements can be added, removed, or modified after the list is created.
Lists support various operations, such as concatenation (+), repetition (*), and membership testing (in).
Comprahension : -
new_list = [expression for item in iterable if condition]
squares = [x ** 2 for x in range(1, 6)]
append() : method is used to add elements at the end of the list.
clear() : method removes all items from the List making it an empty/null list.
count() : method returns the count of the occurrences of a given element in a list.
Extend(): method adds items of an iterable (list, tuple, dictionary, etc) at the end of a list.
index(): searches for a given element from the start of the list and returns the position of the first occurrence.
pop() : function removes elements at a specific index from the list.
remove() : method removes a given element from the list.
reverse() : is an inbuilt method in the Python programming language that reverses objects of the List in place i.e.
it doesn’t use any extra space but it just modifies the original list.
sort(): method sorts the elements of a list. It sorts in ascending order by default but can also sort values in
descending order or in a custom manner using its parameters.
min(): function returns the smallest of the values or the smallest item in an iterable passed as its parameter
max(): function returns the largest item in an iterable or the largest of two or more arguments.
Dictionary Methods
dictionary {} is a collection of key-value pairs that is unordered and mutable, meaning that key-value
pairs can be added, removed, or modified after the dictionary is created.
Individual elements of a dictionary can be accessed using square bracket notation [] with the key.
Comprahension:
{key_expression: value_expression for item in iterable if condition}
squares_dict = {x: x**2 for x in range(1, 6)}
clear(): method removes all items from the dictionary.
fromkeys(): function returns the dictionary with key mapped and specific value. It creates a new dictionary from
the given sequence with the specific value.
seq = ('a', 'b', 'c') print(dict.fromkeys(seq, None)) O/P : {'a': None, 'b': None, 'c': None}
get(): Method return the value for the given key if present in the dictionary. If not, then it will return None. ex: d
= {'coding': 'good', 'thinking': 'better'}print(d.get('coding')) O/P: good
keys(): Method returns a view object that displays a list of all the keys in the dictionary .
pop(): method removes and returns the specified element from the dictionary.
popitem(): method removes the last inserted key-value pair from the dictionary and returns it as a tuple.
setdefault(): returns the value of a key (if the key is in dictionary). Else, it inserts a key with the default value to
the dictionary.
d = {'a': 97, 'b': 98} -- print("setdefault() returned:", d.setdefault('b', 99)) -- print("After using setdefault():", d)
O/P: setdefault() returned: 98 -- After using setdefault(): {'a': 97, 'b': 98}
values(): method that returns a view object.
update(): method updates the dictionary with the elements from another dictionary object or from an
iterable of key/value pairs.
String Methods
string is a sequence of characters enclosed within either single quotes (') or double quotes ("). Strings
are immutable, meaning they cannot be modified after creation.
capitalize(): Converts the first character of the string to a capital (uppercase) letter
casefold(): conver to lower case
lower():Converts all uppercase characters in a string into lowercase
center(): add the spaceby default or specifed string. new_string = string.center(24)
count(): Returns the number of occurrences of a substring in the string.
encode():Encodes strings with the specified encoded schem -- print("¶".encode('utf-8'))
endswith():Returns “True” if a string ends with the given suffix.
expandtabs():Specifies the amount of space to be substituted with the “\t” symbol in the string string = "\t\
tCenter\t\t" print(string.expandtabs())
find(): Returns the lowest index of the substring if it is found
rfind(): Returns the highest index of the substring
format(): Formats the string for printing it to console. print(" I am {} years".format(18))
format_map(): Formats specified values in a string using a dictionary
index() : Returns the position of the first occurrence of a substring in a string
string.index('txt'),
rindex(): Returns the highest index of the substring inside the string. (from right)
isalnum(): Checks whether all the characters in a given string is alphanumeric or not
isalpha(): Returns “True” if all characters in the string are alphabets
isdecimal():Returns true if all characters in a string are decimal
isdigit(): Returns “True” if all characters in the string are digits
islower():hecks if all characters in the string are lowercase
isnumeric(): turns “True” if all characters in the string are numeric characters
isprintable(): Returns “True” if all characters in the string are printable or the string is empty
isspace(): Returns “True” if all characters in the string are whitespace characters
istitle() : Returns “True” if the string is a title cased string
isupper(): Checks if all characters in the string are uppercase
join(): Returns a concatenated String
str = '-'.join('hello') o/p: h-e-l-l-o, list1 = ['g', 'e', 'e', 'k', 's'] print("".join(list1)) o/p : geeks
list1 = " geeks " print("$".join(list1) op: $g$e$e$k$s$,
list1 = {'1', '2', '3', '4', '4'} s = "-#-" s = s.join(list1) o/p = "1-#-3-#-2-#-4
ljust(): Left aligns the string according to the width specified
string = 'geeks' length = 8 fillchar = '*' print(string.rjust(length, fillchar)) O/P:/***geeks
rjust(): Right aligns the string according to the width specified
strip(): Returns the string with both leading and trailing characters
lstrip(): Returns the string with leading characters removed
rstrip(): Removes trailing characters
string = "++++x...y!!z* geeksforgeeks" print(string.lstrip("+.!*xyz")) O/P: geeksforgeeks
partition(): Splits the string at the first occurrence of the separator and returns in tuple.
str = "I love Geeks for geeks" print(str.partition("for")) O/P: ('I love Geeks ', 'for', ' geeks')
rpartition(): Split the given string into three parts
replace(): Replaces all occurrences of a substring with another substring.
str.replace('he','lo)
split(): method is used to split a string into a list of substrings based on a delimiter.
rsplit(): Split the string from the right by the specified separator
splitlines(): Split the lines at line boundaries
string = "Welcome everyone to\rthe world of Geeks\nGeeksforGeeks"
print (string.splitlines( ))
O/P :- ['Welcome everyone to', 'the world of Geeks', 'GeeksforGeeks']
startswith(): Returns “True” if a string starts with the given prefix
swapcase(): Converts all uppercase characters to lowercase and vice versa
title(): Convert string to title case
translate(): Modify string according to given translation mappings
upper(): Converts all lowercase characters in a string into uppercase
zfill(): Returns a copy of the string with ‘0’ characters padded to the left side of the string
text = "geeks for geeks" print(text.zfill(25)) o/P: 0000000000geeks for geeks