2. DATA STRUCTURES IN PYTHON
Data Structures in Python :
Lists
Dictionary
Tuples
Sets
3. LISTS
List is most versatile datatype available in Python, written as a list of comma-
separated values (items) between square brackets.
Items in a list can be Heterogenous types(need not be of the same type).
Lists are mutable
Concatenation produces a new lists.
Append function extends a list with a new value without changing it.
4. LISTS ARE MUTABLE
A mutable object can be changed after it's created, and an immutable object
cannot be changed after its created.
Examples of mutable objects are dictionary,lists etc
Example of lists in mutable form is:
5. LIST FUNCTIONS
list. append ( x) :Add an item to the end of the list.
list. extend ( L): Extend the list by appending all the items in the given list.
list. insert ( i, x): Insert an item at a given position.
list. remove ( x) : Remove the first item
from the list whose value is x.
It gives an error if there is no such item.
6. LIST FUNCTIONS
list. pop ( [i]): Remove the item at the given position in the list, and return it.
list. clear ( ): Remove all items from the list. Equivalent to del a[:] .
Not supported in python 2.X.
list.reverse(): Reverse a given list.
list. index ( x): Return the index in the list of the first item whose value is x. It is an
error if there is no such item.
list. count ( x): Return the number of times x appears in the list.
list. sort ( ): Sort the items of the list in place.
7. DICTIONARY
Dictionary is defined as an unordered set of key: value pairs, with the
requirement that the keys are unique .
Dictionary is a Mutable datatype.
Dictionaries are sometimes found in other languages as “associative memories”
or “associative arrays”.
Dictionaries are indexed by keys, which can be any immutable type or could be
a string.
A pair of braces creates an empty dictionary: {} , not [].
INITIALISATION: example be
Keys could be a string in dictionary. Example
8. DICTIONARY
We can nest dictionaries. Example:
Directly assign values to a dictionary.
Dictionary comprehensions can be used to create dictionaries from arbitrary key
and value expressions:
The dict() constructor builds dictionaries directly from sequences of key-value
pairs:
9. TUPLES
Tuple is a sequence data type.
Tuples are immutable, and usually contain a heterogeneous sequence of
elements.
Simultaneous assignment is possible in tuples.
In tuple, we can assign a tuple of value to a name.
10. TUPLES
Tuples may be nested.
A tuple consists of a number of values separated by commas.
Extract positions in tuples using slices.
11. SETS
A set is an unordered collection with no duplicate elements.
Set objects also support mathematical operations like union, intersection,
difference, and symmetric difference.
Curly braces or the set() function can be used to create sets.
Example:
Creates an empty set using
Set membership in sets
We can convert a list into sets.
12. SETS OPERATIONS
Union : union of two sets is done using “set1|set2”
Intersection : intersection of two sets can be done using “set1&set2”
Set difference: In this, elements present in set2 is not included in the resultant set.
It can be don using “set1-set2
Exclusive or: The syntax for exclusive or is “set1^set2”
13. STRINGS
String is defined as a sequence or list of characters.
String is immutable in nature means once defined , they cannot be changed.
str is the type for strings in python.
Define strings using quotes (“ or ‘ or “““)
>>> st = “Hello World”
>>> st = ‘Hello World’
>>> st = “““This is a multi-line
string that uses triple quotes.”””
‘ ‘ can be used to escape quotes:
14. STRINGS
The string is enclosed in double quotes, if the string contains a single quote
and no double quotes, otherwise it is enclosed in single quotes.
The print() function produces a more readable output, by omitting the enclosing
quotes and by printing escaped and special characters:
‘n’ is used to place a string in newline.
15. STRINGS
If you don’t want characters prefaced by to be interpreted as special characters,
you can use raw strings by adding an r before the first quote:
Two or more string literals (i.e. the ones enclosed between quotes) next to each
other are automatically concatenated.
Attempting to use an index that is too large
result in an error.
16. ACCESSING A STRINGS
To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring.
Example −
18. OPERATIONS ON STRINGS
CONCATENATION (+) :
adds value on the either sde of operator.
REPETITION (*) :
creates new strings,concatenating multiple copies of the same strings.
SLICE ([]) :
gives the character from the given index
RANGE SLICE ([ :]) :
gives the character from the given range.
19. OPERATIONS ON STRINGS
MEMBERSHIP (in) or (not in) : membership returns true or false if the character
exist in the given string.
length (len): It is used to find the length of the string.
upper() : upper() is used to uppercase the string .
lower() : lower() operation is used to lowercase the string.
THERE ARE MANY MORE OPERATIONS ON STRINGS
20. MODIFYING STRINGS
Cannot update a string “in place” as strings are immutable in nature.
Example:
Instead ,use slices and concatenation for modification of strings:-
Example :
21. SLICING IN STRINGS
A slice is a segment of string.
Slicing allows you to obtain substring
Syntax:
Str[start : end]
Start: substring start from this element
End: end of substring excluding the element at this index
S[i:j] starts at s[i] and ends at s[j-1]
S[:j] means start at s[0], so s[0:j]
S[i:] means ends at s[len(s)-1]
22. STRING FORMATTING
str.format () is used to format the string.
Examples: Replace argument by position in message string.
Replace argument by names in message string.