Unit 3
Unit 3
Python Complex data types: Using string data type and string operations,
Defining list and list slicing, Use of Tuple data type. String, List and Dictionary,
Manipulations Building blocks of python programs, string manipulation
methods, List manipulation. Dictionary manipulation, Programming using
string, list and dictionary in-built functions. Python Functions, Organizing
python codes using functions.
What is a String?
String can be defined as a sequence of characters, and that's the most basic
explanation of string that you can provide. In this definition, we can see two
important terms, first being sequence and other is characters. What
is Sequence data type and how Strings are a type of sequence. Just for revision, in
python, Sequence is a data type which is made up of several elements of same type,
i.e., integers, float, characters, strings etc.
string operations:
Operations on String
String handling in python probably requires least efforts. Since in python, string
operations have very low complexity compared to other languages. Let's see how we
can play around with strings.
1. Concatenation: No, wait! what? This word may sound a bit complex for
absolute beginners but all it means is - to join two strings. Like to
join "Hello" with "World", to make it "HelloWorld". Yes, that's it.
HelloWorld
Repetition: Suppose we want to write same text multiple times on console. Like
repeat "Hi!" a 100 times. Now one option is to write it all manually, like "Hi!Hi!
Hi!..." hundred times or just do the following:
Suppose, you want the user to input some number n and based on that you want a
text to be printed on console n times, how can you do it? It's simple. Just create a
variable n and use input() function to get a number from the user and then just
multiply the text with n.
TextTextTextTextText
True
2. not in keyword: This is just the opposite of the in keyword. You're pretty smart
if you guessed that right. Its implementation is also pretty similar to
the in keyword.
4.
5. False
Hence, in such situation, to convert a numeric string into float or int datatype, we can
use float() and int() functions.
numStr = '123'
numFloat = float(numStr)
numInt = int(numFloat)
Slicing
Slicing is yet another string operation. Slicing lets you extract a part of any string
based on a start index and an end index. For example, if we have a string This is
Python tutorial and we want to extract a part of this string or just a character, then
we can use slicing. First lets get familiar with its usage syntax:
string_name[starting_index : finishing_index :
character_iterate]
starting_index is the index of the beginning character which you want in your
sub-string.
finishing_index is one more than the index of the last character that you want
in your substring.
>>> print(str[0:10:2]);
A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9
Copy
Here slicing will be done from 0th character to the 4th character (5-1) by
iterating 1 character in each jump.
Now, remove the last number and the colon and just write this.
Copy
You'll see that output are both same.
You can practice by changing the values. Also try changing the value of the character
iterate variable to some value n, then it will print every nth character from starting
index to the final index.
find(subString)
In case you want to find the position of any character or of a subString within any
given string, you can use the find function. It's implementation is a little different than
a normal function but it's not tough to understand. Obviously to find a subString in a
string, we will have to provide both the main string and the subString to be found, to
the funtion. For Example,
>>> s = "Hello"
>>> ss = "He"
Since, He is present at the beginning of the string Hello, hence index 0 is returned as
the result. It can be directly implemented/used as follows(in case you hate useless
typing; which every programmer do):
string_name.lower()
lower() function is used to convert all the uppercase characters present in a string into
lowercase. It takes a string as the function input, however the string is not passed as
argument. This function returns a string as well.
hello, world
string_name.upper()
upper() is used to turn all the characters in a string to uppercase.
HELLO, WORLD
string_name.islower()
islower() is used to check if string_name string is in lowercase or not. This functions
returns a boolean value as result, either True or False.
Copy
True
string_name.isupper()
isupper() is used to check if the given string is in uppercase or not. This function also
returns a boolean value as result, either True or False.
Copy
True
string_name.replace(old_string, new_string)
replace() function will first of all take a string as input, and ask for some subString
within it as the first argument and ask for another string to replace that subString as
the second argument. For Example,
Hello, India
string_name.split(character, integer)
Suppose you're having a string say,
Copy
Now we can use the split() function to split the above declared string.
If we choose to split the string into two substring from the exclamation mark !. We
can do that by putting an exclamation mark ! in the character argument. It will
basically split the string into different parts depending upon the number of
exclamation marks ! in the string. All the sub-pieces of the string will be stored in a
list. Like,
Copy
You can store these values to another variable and access each element of it like this:
Copy
Hello World
Lists in Python
In the last section, we discussed about strings and the various properties and
functions of strings, like how it can be thought of as a collection of various characters
just like a list. In other words, the list is an ordered set of values enclosed in square
brackets [ ].
An important difference to be noted is that list is mutable, i.e. it's values can be
modified.
As it is nothing but a set of values, we can use the index in square brackets [ ] to
identify an value belonging to the list.
The values that make up a list are called its elements, and they can be of any type.
We can also say that list data type is a container that holds a number of elements in a
given order. For accessing an element in the list, indexing is used, which can be
called from both forward and backward direction (similar to strings).
Constructing a List
As already explained, the list is a collection of similar type of data. This data can be
an integer, a float, a complex number, a String or any legitimate datatype in
python. The list is always provided with some name, similar to a variable, and each
element is accessed by their index number. Python has both forward and backwards
index number, so for each element there exists one positive and one negative
number to access that element (discussed in the next topic). While defining a list, we
have to enclose each element of the list within square brackets, and each element is
separated by commas.
Suppose, if you want to create an empty list (which is possible in case you want to
add the elements later in the program or when user gives the input), then you can
initialize it by declaring empty square brackets,
>>> myEmptyList = []
Copy
A list of float values,
Copy
A list of characters,
Copy
A list of strings,
Copy
And now you want to create a new list which consists some or all the elements
of myList1, then you can you do a direct assignment for complete copying of
elements or use slicing, and take only some elements.
Suppose you want to add serial whole numbers (i.e., 0, 1, 2, 3, ...) into your list and
just don't want to write all of them one by one, do not worry, there is a shortcut for
doing this.
Copy
This will create a list having numbers 5, 6, 7, 8 i.e., argument's first number to
the (argument's last number - 1).
Suppose you want to create a list with squares of all whole numbers. Although there
exists various programming approaches for this problem but here is a one line
method in python. We will be introducing something new, so it can get a little tricky.
The final list will contain elements like [0, 1, 4, 9, 16], i.e. x**2 where x is varying
from 0 to (5-1).
for is the keyword here that you may not be familiar with. for is one of the keywords
that makes programming do a lot of mundane and redundant task for a
programmer, for example, it can create loops of execution. Although there will be a
whole chapter dedicated to this, the important thing to note here is that for is the
keyword which is responsible for iterating (or repeating) x in range 0 to 4 and finally
storing the iterated value's square i.e. (x ) in the list.
2
Appending to a List
Appending basically means adding to the existing. If you remember we told you
how you can create an empty list in python by just declaring an empty square
bracket. Now, what to do when you actually have to insert some elements inside the
list? This is where append function comes in use. You can add any number of elements
to the end of the list in one line without any hassle.
>>> emptyList = []
>>> emptyList.append('F.R.I.E.N.D.S')
>>> emptyList.append('Seinfeld')
So, that will basically create a list of some of the best sitcoms (and isn't empty
anymore). If you print the list.
>>>print (emptyList)
['The Big Bang Theory', 'F.R.I.E.N.D.S', 'How I Met Your Mother', 'Seinfeld']
Indexing of elements
We have already covered about using index to access the sequence of characters in a
string in the string tutorial. Similarly, in python, index numbers can be used to access
the elements of a list too. Let's create a list of strings and try to access individual
strings using index numbers. Here is an example,
As you can see in the code above, we have a list with 7 elements. To find the number
of elements in a list, us the function len just like for strings.
For every element in the list, following are the index numbers that we should use: (try
to understand how we assigned the index numbers.)
Tuples are immutable general sequence objects that allows the individual items to be
of different types. •Equivalent to lists, except that they can’t be changed.
List Comprehension
List comprehension offers a shorter syntax when you want to create a new
list based on the values of an existing list.
Example:
Based on a list of fruits, you want a new list, containing only the fruits with
the letter "a" in the name.
Without list comprehension you will have to write a for statement with a
conditional test inside:
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
print(newlist)
The Syntax
newlist = [expression for item in iterable if condition == True]
Condition
The condition is like a filter that only accepts the items that valuate to True.
Example
Only accept items that are not "apple":
The condition if x != "apple" will return True for all elements other than
"apple", making the new list contain all fruits except "apple".
The condition is optional and can be omitted:
Example
With no if statement:
Iterable
The iterable can be any iterable object, like a list, tuple, set etc.
Example
You can use the range() function to create an iterable:
Example
Accept only numbers lower than 5:
Expression
The expression is the current item in the iteration, but it is also the outcome,
which you can manipulate before it ends up like a list item in the new list:
Example
Set the values in the new list to upper case:
Example
Set all values in the new list to 'hello':
Example
Return "orange" instead of "banana":
print (myDict)
Output :
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
print(dic)
{'O': 'ooo', 'N': 'nnn', 'I': 'iii', 'C': 'ccc', 'D': 'ddd', 'G':
'ggg'}
def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')
Output:
Hello
Welcome
to
GeeksforGeeks
Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks
def myFun(**kwargs):
for key, value in kwargs.items():
print("%s == %s" % (key, value))
# Driver code
myFun(first='Geeks', mid='for', last='Geeks')
first == Geeks
mid == for
last == Geeks