04 Data - Structure String List Part1
04 Data - Structure String List Part1
_________________________________________________
Python has a few Python Specific Data Structures (List, Tuple, Dictionary) and non- Python Specific
Data Structures (String, sets). All these data structures are quite sophisticated and help us to store a
collection of values rather than a single one. For this course, we will discuss String, List, Tuple, and
Dictionaries. Even though file reading is not part of the data structures, the ability to store and fetch
previously-stored information is very essential for any language. SO we have covered it at the end of
this chapter.
1
Strings
_________________________________________________
String is a sequence of ordered characters (alphabets-lower case, upper case, numeric values, special
symbols) represented with quotation marks (single('), double(''), triple(' ' ', '' '' '')) at the beginning and
end. The character order is always from left to right. For example: using single quotes ('CSE110'),
double quotes ("CSE110") or triple quotes ('''CSE110''' or """CSE110"""), "Hello CSE110 students".
Example:
Output:
We Love Coding in Python.
But after mastering Python,
should we call ourselves, "Snake charmers"
or "Python programmers"?
2
String printing special cases
1) In the last single line example, we had to print a pair of quotation marks as a part of the output.
Since Python has 3 options (single('), double(''), triple(' ' ', '' '' '') quotation) for representing String, we
can easily print a pair quotation, using the alternative one. For example:
Code Output
2) Assume, you have to print She asked, "Aren't you late for work?". Here you have to print a pair of
quotation marks as well as one single quotation mark, so the previous way of string printing will not
work here. This problem can be solved by using triple quotes(' ' ', '' '' ''), representing special
characters with a preceding backslash which is called an escape character. Using an escape character,
or a preceding backslash tells the interpreter to consider the character following the backslash as a
printable character. For example, putting \" will print ", putting \' will print ', and putting \\ will
print \.
To print our example, we can use multiple variations of escape characters. We can either put the
entire string (along with the double quotes) inside a single quote and then use the escape character to
print the single quote mark in the middle. Or in the opposite manner, we can put the entire string in
double-quotes, and print the double quote mark in the string using escape characters. For example:
Code Output
print('''She asked, "Aren\'t you She asked, "Aren't you late for
late for work?"''') work?"
print('She asked, "Aren\'t you She asked, "Aren't you late for
late for work?"') work?"
print("She asked, \"Aren't you She asked, "Aren't you late for
late for work?\"") work?"
Note: Details about escape characters and escape sequences are provided in the link below.
Link: https://docs.python.org/2.0/ref/strings.htmlEmpty String
3
Empty String
Strings represented with only two single('') or two double("") quotes with no characters in between
are called Empty String. For example:
Code Output
String indexing
For accessing individual characters within a string, python uses square brackets to enclose the index
value or the position of that particular character
Indexing can be done in two ways:
1. Positive indexing:
It is used to access the characters from the left side of a string. Positive indexing always starts
from 0 ( left-most character of the string ) and ends at the last character of the string.
2. Negative indexing:
It is used to access the characters from the right side of a string. Negative indexing always
starts from -1 ( rightmost character of the string ) and ends at the first character of the string.
Positive 0 1 2 3 4 5 6 7 8 9 10 11 12
indexing
L o v i n g C S E 1 1 0
Here, in the example above indexing of “Loving CSE110” is shown. The positive indexing starts at 0
with ‘L’ and ends at ‘0’ with 12. The negative indexing starts at -1 with ‘0’ and ends at ‘L’ with -13. If
anything out of the valid range is tried to be accessed, the program will yield an IndexError.
Additionally, if any other data type except an integer is entered as an index, TypeError will rise.
4
For example:
Code Output
print(text[-4]) E
print(text[13]) IndexError
print(text[-15]) IndexError
print(text[1.5]) TypeError
String slicing
Slicing is used for getting a substring of a particular string. In more general terms, it is used for
accessing a particular range of characters. Colon(:) is used as a slicing operator.
Example:
Code Output
print(text[4:-3]) ng CSE
prints from the 5th character (index 4) to
the 3rd last character (index 10) of the
string
5
print(text[2:12:3]) vgS1
prints from the 2nd character (index 2) to
the 13th character (index 12) of the
string, with a step size of 3.
print(text[-9:-2]) ng CSE1
prints from the 9th last character of the
string (index 4) to the 2nd last character
(index 11) of the string
String Operators
Few of the basic operators discussed in the first chapter work quite differently while working with
strings. In the table below, you will get an idea about their adapted working procedure with strings.
6
not in Membership: Returns True if "ph" not in
the first value is not in the "elephant"
second. Otherwise, returns Output: False
False.
String Immutability
Immutable means once it has been created its value cannot be changed. So, each time we have to modify the
values, we need to make a copy of the original one and make changes to the duplicate one. For example, the
String’s built-in methods. But it has an advantage that its elements can be accessed very fast. For example:
Code Output
Here, from the example, we can see that Strings do not allow any kind of alteration to their values as
Strings are immutable.
String methods
Python has a good number of built-in methods or functions to utilize Strings. Because of string
immutable property, these methods do not change the original String rather returns a new String copy
every time. Among these methods, the most frequently used ones have been mentioned in the table
below.
7
Output:
Hello World
hello world
Output:
Hello World
HELLO WORLD
Output:
BracU CSE110
BracU CSE110
Output:
BracU CSE110
BracU CSE110
Output:
BracU CSE110
BracU CSE110
8
Output:
Bangladesh
2
Output:
Hello
True
Output:
Hello
False
Output:
Bangladesh
1
Output:
Hello
Hentnto
Note: Details about String methods will be found in the link below.
Link: https://docs.python.org/2/library/stdtypes.html#string-methods
9
ASCII
ASCII stands for American Standard Code for Information Interchange. In order to store and
manipulate data, it needs to be in binary values. Here, in ASCII 128 English characters and different
symbols are represented with a 7-bit binary number, with a decimal value ranging from 0 to 127.
For example, 65 is the ASCII value of the letter ‘A’, and 97 is the ASCII value of the letter ‘a’.
Two built-in Python functions ord() and chr() are used to make the conversions between ASCII values
and characters. The ord() converts characters to ASCII values and chr() converts ASCII values to
characters.
Example: Output
chr(98) 'b'
chr(66) 'B'
ord('a') 97
ord('%') 37
10
Lists
_________________________________________________
Data structures are containers that organize and group data types together in different ways. A list in
python is one of the most common and basic data structures that are written in square brackets “[]”
with elements stored inside separated by commas. A list is also ordered and mutable. For example:
Code Output
list = ["Hi!", "Welcome", ['Hi!', 'Welcome', 'to', 'CSE',
"to", "CSE", "110"] '110']
print(list)
Mutability
The word “mutability” in python means the ability for certain types of data to be changed without
recreating it entirely. It makes the program run more efficiently and quickly. For example:
Code Output
beatles = ["John", "Paul", "Alonzo", "Ringo"] ['John', 'Paul',
'Alonzo',
#Before Modification 'Ringo']
print(beatles)
Necessity of Lists
Lists don’t need to be always homogeneous. They maintain the order of sequences whose values are
not fixed. We can easily access and modify values inside a list. For example, adding value or removing
is possible in a list. On the other hand, tuples are immutable and cannot be changed (you will get an
explanation in the next section named "tuple"). Again, in python lists and strings are quite similar. We
can use the “for” loop to iterate over lists, “+” plus operator in order to concatenate and use in a
keyword to check if the sequence contains a value.
11
2. In a list, negative indexing means beginning from the end. Example: -1 refers to the last item,
-2 refers to the second-last item, etc..
Code Output
example_list = ["Kitkat", Hersheys
"Oreo","Hersheys"] Oreo
print(example_list[-1])
print(example_list[-2])
3. While specifying a range in a list, the return value will give a new list with the specified items:
Code Output
example_list = ["Hersheys","Kitkat", "Oreo", ['Oreo',
"MIMI", "Cadbury", "Monchuri-Milk Candy"] 'MIMI',
'Cadbury']
print(example_list[2:5])
4. While specifying a range of negative indexes in a list, we can start the search from the end of a
list. Given example returns the items from index -5 (included) to index -1 (excluded).
Code Output
example_list = ["Hersheys","Kitkat", "Oreo", ['Kitkat',
"MIMI", "Cadbury", "Monchuri-Milk Candy"] 'Oreo', 'MIMI',
'Cadbury']
print(example_list[-5:-1])
5. By leaving out the start value, the range will start from the first item of the list. Again, by
leaving out the end value, the range will go on to the end of the list.
Code Output
#Example-1)leaving out the start value: ['Hersheys',
'Kitkat',
example_list = ["Hersheys","Kitkat", "Oreo", 'Oreo']
"MIMI", "Cadbury", "Monchuri-Milk Candy"]
print(example_list[:3])
print(example_list[4:])
12
6. Since lists are mutable, we can change the items inside it.
Code Output
example_list = ["Hersheys","Kitkat", "Oreo", ['Oreo',
"MIMI", "Cadbury", "Monchuri-Milk Candy"] 'MIMI',
'Cadbury']
print(example_list[2:5])
Example: Output
for i in example_list:
print(i)
13
example_list = ["Hersheys","Kitkat",
"Oreo", "MIMI"]
if "MIMI" in example_list:
print("Yes,MIMI is in the list")
example_list = ["Hersheys","Kitkat",
"Oreo", "MIMI"]
print(len(example_list))
print('Hersheys' in example_list)
print('Cadbury' in example_list)
14
Built-in Methods of Lists with Examples:
15
Slicing
We can understand slicing by visualizing the index to be in between the elements as shown below.
How the slicing works have been explained in detail in the String chapter. The slicing mechanism
works identically in all the data structures.
String F A N T A S T I C
Positive indexing 0 1 2 3 4 5 6 7 8
Negative indexing -9 -8 -7 -6 -5 -4 -3 -2 -1
If we want to access a range, we need two indices that will slice that portion from the list. For
example:
Example: Output
my_list =
['F','A','N','T','A','S','T','I','C']
print(my_list[2:5])
16
Style Guide for Python Code
______________________________________________
For every programming language, there are few coding conventions followed by the coding
community of that language. All those conventions or rules are stored in a collected document
manner for the convenience of the coders, and it is called the “Style Guide” of that particular
programming language. The provided link gives the style guidance for Python code comprising the
standard library in the main Python distribution.
17