0% found this document useful (0 votes)
75 views

Unit 3

This document discusses Python string data types and operations. It defines what a string is, provides examples of string input and output, and describes various string operations like concatenation, repetition, checking for existence of a substring, slicing, and built-in string functions like len(), lower(), upper(), find(), replace(), split(), etc. It also introduces lists as another Python data type that is ordered and mutable, allowing values to be accessed and modified using indexes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Unit 3

This document discusses Python string data types and operations. It defines what a string is, provides examples of string input and output, and describes various string operations like concatenation, repetition, checking for existence of a substring, slicing, and built-in string functions like len(), lower(), upper(), find(), replace(), split(), etc. It also introduces lists as another Python data type that is ordered and mutable, allowing values to be accessed and modified using indexes.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

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.

Using string data type and string operations:

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.

>>> mystring = "This is not my first String"

>>> print (mystring);

This is not my first String

string operations:

>>> print (mystring[0]);

Input and Output for String

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.

>>> print ("Hello" + "World");

HelloWorld

>>> s1 = "Name Python "

>>> s2 = "had been adapted "

>>> s3 = "from Monty Python"

>>> print (s1 + s2 + s3)

Name Python had been adapted from Monty Python

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:

>>> print ("Hi!"*100)

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.

>>> n = input("Number of times you want the text to repeat: ")

Number of times you want the text to repeat: 5


>>> print ("Text"*n);

TextTextTextTextText

Check existence of a character or a sub-string in a string: The keyword in is used


for this. For example: If there is a text India won the match and you want to check
if won exist in it or not. Go to IDLE and try the following:

>>> "won" in "India won the match"

True

1. Amongst other datatypes in python, there is Boolean datatype which can


have one of the possible two values, i.e., either true or false. Since we are
checking if something exists in a string or not, hence, the possible outcomes
to this will either be Yes, it exists or No, it doesn't, therefore
either True or False is returned. This should also give you an idea about
where to use Boolean datatype while writing programs.

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.

3. >>> "won" not in "India won the match"

4.

5. False

Converting String to Int or Float datatype and vice versa

This is a very common doubt amongst beginners as a number when enclosed in


quotes becomes a string in python and then if you will try to perform mathematical
operations on it, you will get error.
numStr = '123'
In the statement above 123 is not a number, but a string.

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]

 String_name is the name of the variable holding the string.

 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.

 character_iterate: To understand this, let us consider that we have a


string Hello Brother!, and we want to use the slicing operation on this string to
extract a sub-string. This is our code:

 >>> str = "Hello Brother!"

 >>> print(str[0:10:2]);

 Now str[0:10:2] means, we want to extract a substring starting from the


index 0 (beginning of the string), to the index value 10, and the last parameter
means, that we want every second character, starting from the starting index.
Hence in the output we will get, HloBo.
 H is at index 0, then leaving e, the second character from H will be printed,
which is l, then skipping the second l, the second character from the first l is
printed, which is o and so on.

 It will be more clear with a few more examples:


 Let's take a string with 10 characters, ABCDEFGHIJ. The index number will
begin from 0 and end at 9.

A B C D E F G H I J
0 1 2 3 4 5 6 7 8 9

Now try the following command:

>>> print s[0:5:1]

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.

>>> print (s[0:5]);

>>> print (s[0:5]);

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.

Built-in String Functions in Python


len(string)
len or length function is used to find the character length of any string. len returns a
number and it takes a string as an argument. For Example,
>>> s = "Hello"

>>> print (len(s))

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"

>>> print (s.find(ss))

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):

>>> print ("Hello".find("He"))

>>> print ("Hello".find("He"))

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.

>>> print ("Hello, World".lower());

hello, world

string_name.upper()
upper() is used to turn all the characters in a string to uppercase.

>>> print ("Hello, World".upper());

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.

>>> print ("hello, world".islower())

Copy

True

>>> print ("Hello, World".islower());

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.

>>> print ("HELLO, WORLD".isupper());

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,

>>> print ("Hello, World".replace("World", "India"));

Hello, India

string_name.split(character, integer)
Suppose you're having a string say,

>>> mystring = "Hello World! Welcome to the Python tutorial"

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,

>>> print (mystring.split("!"))

Copy

['Hello World', ' Welcome to the Python tutorial']

You can store these values to another variable and access each element of it like this:

>>> myNEWstring = mystring.split("!")

>>> print (myNEWstring[0]);

>>> print (myNEWstring[1]);

Copy

Hello World

Welcome to the Python tutorial

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 = []

For example, list of some integers will be,

>>> myIntegerList = [9, 4, 3, 2, 8]

Copy
A list of float values,

>>> myFloatList = [2.0, 9.1, 5.9, 8.123432]

Copy
A list of characters,

>>> myCharList = ['p', 'y', 't', 'h', 'o', 'n']

Copy
A list of strings,

>>> myStringList = ["Hello", "Python", "Ok done!"]


Deriving from another List

Suppose there is an existing list,

>>> myList1 = ['first', 'second', 'third', 'fourth', 'fifth']

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.

For complete copying,

>>> myList2 = myList1

Use slicing, for copying only the first three elements,

>>> myList2 = myList1[0:3]

For copying last three elements,

>>> myList2 = myList1[-3]

Adding Serial Numbers in a List

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.

For storing 0 to (n-1) numbers in a list use range(n) function.

>>> myList1 = range(9)

Copy

This will create a list with numbers 0 to 8 inside it.


>>> myList1 = range(5, 9)

This will create a list having numbers 5, 6, 7, 8 i.e., argument's first number to
the (argument's last number - 1).

This range() function can be used for various usecases.

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.

>>> myQuickList = [x**2 for x in range(5)]

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('The Big Bang Theory')

>>> emptyList.append('F.R.I.E.N.D.S')

>>> emptyList.append('How I Met Your Mother')

>>> 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,

>>> fruitsList = ["Orange", "Mango", "Banana", "Cherry",


"Blackberry", "Avocado", "Apple"]

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.

>>> print (len(fruitsList));

For every element in the list, following are the index numbers that we should use: (try
to understand how we assigned the index numbers.)

Element Forward index Backward index


Orange 0 -7
Mango 1 -6
Banana 2 -5
Cherry 3 -4
Blackberry 4 -3
Avocado 5 -2
Apple 6 -1
L.append() : Adds one item to the end of the list.
•L.extend() : Adds multiple items to the end of the list.
•L.pop(i) : Remove item ‘i’ from the list. Default:Last.
•L.reverse() : Reverse the order of items in list.
•L.insert(i,item): Inserts ‘item’ at position i.
•L.remove(item) : Finds ‘item’ in list and deletes it from the list.
•L.sort(): Sorts the list in-place i.e., changes the sequence in the list.

Use of Tuple data type. String, List and Dictionary:

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.

Dictionaries are unordered collections of objects, optimized for quick searching. •


Instead of an index, objects are identified by their ‘key’. •Eachitemwithin a dictionary
is a ‘key’:’value’ pair. •Equivalent to hashes or associative arrays in other languages.
•Like lists and tuples, they can be variable-length, heterogeneous and of arbitrary
depth. • ’Keys’ are mapped to memory locations by a hash function.

D.keys() : List of keys


•D.values():Listofvalues
•D.clear() : remove all items
•D.update(D2) : Merge key values from D2 into D. NOTE: Overwrites any matching
keys in D.
•D.pop(key) : returns the value of given key and removes this key:valuepair from
dictionary.

Summary: Lists vs. Tuples vs. Dictionaries


All three data types stores a collection of items.
•All three allow nesting, heterogeneity and arbitrary depth.
•Choice of data type depends on intended use:
• Lists: Best suited for ordered collections of items where the order or the items
themselves may need to be changed.
• Tuples: Best suited for maintaining a copy of the collection that will not be
accidentally changed during the program.
• Dictionary : Best suited for storing labeled items, especially in collections where
frequent searching is required.

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:

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]


newlist = []

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"]

newlist = [x for x in fruits if "a" in x]

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":

newlist = [x for x in fruits if x != "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:

newlist = [x for x in fruits]

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:

newlist = [x for x in range(10)]

Same example, but with a condition:

Example
Accept only numbers lower than 5:

newlist = [x for x in range(10) if x < 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:

newlist = [x.upper() for x in fruits]

ou can set the outcome to whatever you like:

Example
Set all values in the new list to 'hello':

newlist = ['hello' for x in fruits]


The expression can also contain conditions, not like a filter, but as a way to
manipulate the outcome:

Example
Return "orange" instead of "banana":

newlist = [x if x != "banana" else "orange" for x in fruits]

Sort List Alphanumerically


List objects have a sort() method that will sort the list alphanumerically,
ascending, by default:

Sort the list alphabetically:

thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]


thislist.sort()
print(thislist)

Sort the list numerically:

thislist = [100, 50, 65, 82, 23]


thislist.sort()
print(thislist)

Python Dictionary Comprehension

Like List Comprehension, Python allows dictionary comprehensions. We can create


dictionaries using simple expressions. A dictionary comprehension takes the
form {key: value for (key, value) in iterable}

Python Dictionary Comprehension Example


Here we have two lists named keys and value and we are iterating over them with
the help of zip() function.

# Python code to demonstrate dictionary


# comprehension

# Lists to represent keys and values


keys = ['a','b','c','d','e']
values = [1,2,3,4,5]

# but this line shows dict comprehension here


myDict = { k:v for (k,v) in zip(keys, values)}

# We can use below too


# myDict = dict(zip(keys, values))

print (myDict)

Output :
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Using fromkeys() Method


Here we are using the fromkeys() method that returns a dictionary with specific keys
and values.
dic=dict.fromkeys(range(5), True)

print(dic)

{0: True, 1: True, 2: True, 3: True, 4: True}

Using dictionary comprehension make dictionary

# Python code to demonstrate dictionary


# creation using list comprehension
myDict = {x: x**2 for x in [1,2,3,4,5]}
print (myDict)

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}


sDict = {x.upper(): x*3 for x in 'coding '}
print (sDict)

{'O': 'ooo', 'N': 'nnn', 'I': 'iii', 'C': 'ccc', 'D': 'ddd', 'G':
'ggg'}

Using conditional statements in dictionary comprehension


Example 1:
We can use Dictionary comprehensions with if and else statements and with other
expressions too. This example below maps the numbers to their cubes that are not
divisible by 4.
# Python code to demonstrate dictionary
# comprehension using if.
newdict = {x: x**3 for x in range(10) if x**3 % 4 == 0}
print(newdict)

{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}

*args and **kwargs in Python


In this article, we will cover what ** (double star/asterisk) and * (star/asterisk) do
for parameters in Python, Here, we will also cover args and kwargs examples in
Python. We can pass a variable number of arguments to a function using special
symbols.
There are two special symbols:

Special Symbols Used for passing arguments in Python:


 *args (Non-Keyword Arguments)
 **kwargs (Keyword Arguments)

What is Python *args?


The special syntax *args in function definitions in Python is used to pass a variable
number of arguments to a function. It is used to pass a non-keyworded, variable-
length argument list.
 The syntax is to use the symbol * to take in a variable number of
arguments; by convention, it is often used with the word args.
 What *args allows you to do is take in more arguments than the number of
formal arguments that you previously defined. With *args, any number of
extra arguments can be tacked on to your current formal parameters

def myFun(*argv):
for arg in argv:
print(arg)
myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:
Hello
Welcome
to
GeeksforGeeks

def myFun(arg1, *argv):


print("First argument :", arg1)
for arg in argv:
print("Next argument through *argv :", arg)

myFun('Hello', 'Welcome', 'to', 'GeeksforGeeks')

Output:
First argument : Hello
Next argument through *argv : Welcome
Next argument through *argv : to
Next argument through *argv : GeeksforGeeks

What is Python **kwargs?


The special syntax **kwargs in function definitions in Python is used to pass a
keyworded, variable-length argument list. We use the name kwargs with the double
star. The reason is that the double star allows us to pass through keyword arguments
(and any number of them).
 A keyword argument is where you provide a name to the variable as you
pass it into the function.
 One can think of the kwargs as being a dictionary that maps each keyword
to the value that we pass alongside it. That is why when we iterate over
the kwargs there doesn’t seem to be any order in which they were printed
out.

Python program to illustrate *kwargs for a variable number of keyword arguments.


Here **kwargs accept keyworded variable-length argument passed by the function
call. for first=’Geeks’ first is key and ‘Geeks’ is a value. in simple words, what we
assign is value, and to whom we assign is key.
 Python3

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy