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

Python Strings and List

The document provides an overview of strings, lists, tuples, sets, and dictionaries in Python, highlighting their characteristics and usage. It explains how to create and manipulate these data structures, including methods and functions associated with them. Additionally, it covers the basics of defining and calling functions in Python, including parameter passing and types of arguments.

Uploaded by

sravanipakala205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Strings and List

The document provides an overview of strings, lists, tuples, sets, and dictionaries in Python, highlighting their characteristics and usage. It explains how to create and manipulate these data structures, including methods and functions associated with them. Additionally, it covers the basics of defining and calling functions in Python, including parameter passing and types of arguments.

Uploaded by

sravanipakala205
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 25

STRINGS IN PYTHON

Strings in Python:

A string is a sequence of characters that can be a combination of letters,


numbers, and special characters. It can be declared in python by using single quotes,
double quotes, or even triple quotes. These quotes are not a part of a string, they
define only starting and ending of the string. Strings are immutable, i.e., they cannot
be changed. Each element of the string can be accessed using indexing or slicing
operations.

In Python, Strings are arrays of bytes representing Unicode characters.


Example:
“srinivas" or ‘hello world‘

Python does not have a character data type, a single character is simply a string
with a length of 1. Square brackets can be used to access elements of the string.

>>> Print(“hello world”)


output : hello world
Accessing characters in String:

In Python, individual characters of a String can be accessed by using the


method of Indexing ie index value ‘0’ on words.

Indexing allows negative address references to access characters


from the back of the String, e.g. -1 refers to the last character, -2 refers to the second
last character, and so on.

While accessing an index out of the range will cause an IndexError.


Only Integers are allowed to be passed as an index, float or other types that will cause
a TypeError.
S R I N I V A S
String -> 0 1 2 3 4 5 6 7
Index values -> -8 -7 -6 -5 -4 -3 -2 -1

Pre defined methods


Built-in Data Structures
Python have 4 types of built-in Data Structures namely List, Dictionary, Tuple, and Set.

LISTS:
Lists are one of the most powerful data structures in python. Lists are
sequenced data types. In Python, an empty list is created using list() function.
They are just like the arrays declared in other languages.
A single list can contain strings, integers, as well as other objects.
Lists can also be used for implementing stacks and queues.
Lists are mutable, i.e., they can be altered once declared. The elements
of list can be accessed using indexing and slicing operations.

In Python Lists are just like dynamically sized arrays, declared in other
languages (vector in C++ and ArrayList in Java).
In simple language, a list is a collection of things, enclosed in [ ] and
separated by commas.
The list is a sequence data type which is used to store the collection of
data.
Tuples and String are other types of sequence data types.
# creating empty list
l=[]
print(l)

# creating list of numbers


l=[1,2,3,4]
print(l)

#creating list of strings


l=["apple","banana","orange"]
print(l)

l=[1,"one",2,"two",3,"three",4,"four"]
Print(l)

Python len() is used to get the length of the list.


# creating empty list
l=[] l1=[1,2,3,4]
print(l) l2=["abc","xyz","pqr"]
print(len(l1))
# creating list of numbers print(len(l2))
l=[1,2,3,4]
print(l) #Accessing elements from a multi-dimensional
list
#creating list of strings l=[[1,2,3,4],[5,6,7,8,9]]
l=["apple","banana","orange"] print(l)
print(l) print(l[0][0])
print(l[1][1])
l=[1,"one",2,"two",3,"three",4,"four"] print(l[1][0])
print(l) print(l[0][2])
print(l[0:2])
print(l[5:6]) # IndexError: list index out of range
print(l[2][0])
Python offers the following list functions:

sort(): Sorts the list in ascending order.

type(list): It returns the class type of an object.

append(): Adds a single element to a list.

extend(): Adds multiple elements to a list.

index(): Returns the first appearance of the specified value.

max(list): It returns an item from the list with max value.

min(list): It returns an item from the list with min value.

len(list): It gives the total length of the list.

cmp(list1, list2): It compares elements of both lists list1 and list2.


# Python program to illustrate a list

# creates a empty list


nums = []
# appending data in list
nums.append(21)
nums.append(40.5)
nums.append("String") Output:
print(nums)
Tuple :
A tuple in Python is similar to a list . The difference between the two is
that we cannot change the elements of a tuple once it is assigned where as we
can change the elements of a list.

Ex:

t1=("apple","banana","orange")
print(t1[1:])
print(t1[0:1])
print(t1) output:
print(t1+t1)
print(t1*2)
print(type(t1))
Set:
Sets are used to store multiple items in a single variable. Set is one of 4 built-in
data types in Python used to store collections of data, the other 3 are List, Tuple, and
Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.

•Note: Set items are unchangeable, but you can remove items and add new items.

Set Items:
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered:
Unordered means that the items in a set do not have a defined order.
Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

Unchangeable:
Set items are unchangeable, meaning that we cannot change the items after the set
has been created.Once a set is created, you cannot change its items, but you can
remove items and add new items.

Duplicates Not Allowed :


Sets cannot have two items with the same value.
1. Using the set() method:
When a set is created using the set() method, only the unique elements are added
to the set, even though the same element is defined twice inside the set() function.
This is because the basic rule of defining a set says that elements have to be unique.

s1 = set([1,2,3,2, 'a', 'b', 'a', ‘x', ‘y', ‘x',])


print(s1)

output: {1, 2, 3, 'a', ’x,’ ’y’, 'b', }

2. Using curly braces and comma-separated values


A set can have multiple types of data in it. Below is an example that shows set with a
single data type. It is followed by an example that shows a set being defined with elements
of different data types.

s2={ 1,2,3,4,1, 'a', ' ab', 'ac', 'bc ‘}

Output:
{1, 2, 3, 4, 'bc', 'ac', 'a', ' ab'}
Method Description
clear() Removes all the elements from the dictionary

copy() Returns a copy of the dictionary

fromkeys() Returns a dictionary with the specified keys and value

get() Returns the value of the specified key

items() Returns a list containing a tuple for each key value pair

keys() Returns a list containing the dictionary's keys

pop() Removes the element with the specified key

popitem() Removes the last inserted key-value pair

setdefault() Returns the value of the specified key. If the key does not exist:
insert the key, with the specified value

update() Updates the dictionary with the specified key-value pairs

values() Returns a list of all the values in the dictionary


Note: As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.

Dictionaries are written with curly brackets, and have keys and values:

Ex:
>>> digits={1:"one",2:"two",3:"three"}
>>> digits
Output: {1: 'one', 2: 'two', 3: 'three'}

Dictionary Items:
Dictionary items are ordered, changeable, and does not allow
duplicates.
Dictionary items are presented in key:value pairs, and can be referred to
by using the key name.
Ordered or Unordered:
Note:As of Python version 3.7, dictionaries are ordered. In Python 3.6 and
earlier, dictionaries are unordered.

When we say that dictionaries are ordered, it means that the items
have a defined order, and that order will not change.
Unordered means that the items does not have a defined order, you
cannot refer to an item by using an index.

Changeable:
Dictionaries are changeable, meaning that we can change, add or
remove items after the dictionary has been created.

Duplicates Not Allowed:


Dictionaries cannot have two items with the same key:
Ex:
car = { "brand": "Ford", "model": “xyz", “color": ”red”, "year": 2020}

print(car)
Python Functions:
A Python function is a reusable, organized block of code that is used to
perform the specific task. The functions are the appropriate way to divide an extensive
program into a useful block. It also provides reusability to our program. A code block
can be reused by calling the function.
All functions are treated as an object in Python, so it is more flexible than other
programming languages.
In Python, there are two types of functions:
Built-in functions – These functions are the part of the Python libraries and packages.
These are also called as pre-defined functions.
User-defined functions – These functions are defined by the user as per their
requirement.

Syntax:

C syntax:
return_type function_name ( paramete
{
body of the function
}
Creating a function:
Below are the basic steps to create a user-defined function.

 def keyword is used to define function followed by the function name.

 Arguments should be written inside the opening and closing parentheses of the
function, and end the declaration with a colon.

 Write the program statements to be executed within the function body.

 The return statement is optional. It should be written at the end of the function.
Creating a Python Function:
We can create a Python function using the def keyword.

# A simple Python function


def fun():
print("Welcome to python ")

Calling a Python Function:


After creating a function we can call it by using the name of the function
followed by parenthesis containing parameters of that particular function.

# A simple Python function defining


def fun():
print(" Welcome to python ")
# code to call a function
fun()
The argument list can contain none or more arguments. The arguments are
also called parameters. The function body contains indented statements. The function
body gets executed whenever the function is called. The arguments can be optional or
mandatory.

Calling a Function
After declaring a function, it must be called using function name followed
by parentheses with appropriate argument.

Note: It is necessary to define a function before calling; otherwise, it will give an error.

Example 1:
def disp():
print(“hello world”)
disp()

Example 2: def sum(a,b): # define a function sum with two argument


c=a+b
return c #returning the value to calling function
z=sum(10,20)
print("The sum is:",z)
Parameter Passing
There are two most common strategies of passing an argument to a function.
Call by Value
This strategy is used in C, C++ or Java but not used in Python. In call by
value, the values of actual parameters are copied to function’s formal parameters, and
both types of parameters are stored in separate memory locations. So if we made any
changes in formal parameters, that changes will not be reflected in actual parameters of
the caller function.
Call by Reference
The functions are called by reference in Python, which means all the changes
performed to the inside the function reflected in an actual parameter.
Types of arguments
There may be several types of arguments, which are listed below
1. Required arguments
2. Default arguments
3. Keyword arguments
4. Variable-length arguments
1. Required Arguments:
The required arguments are those arguments which are mandatory to pass
at the time of function calling with exact match their positions in the function call and
function definition. If the argument is not provided in the function call or made any
changes in arguments position, then Python interpreter will show an error.
def add(a,b): def add(a,b):
c=a+b c=a+b
return c return c
sum=add(10,20) sum=add(10)
Print(sum); Print(sum);
Output: 30 Output: TypeError: add() missing 1 required
positional argument: 'b'

2. Default argument:
The default arguments are those arguments that assign a value with the
argument at the time of function definition. If the argument is not specified at the
time of function call, then it will be initialized with the value which was given in the
definition. For example
def add(a,b=30): #default value def disp(name,age=45):
c=a+b print('My name is:',name)
return c print('My age is',age)
sum=add(10) disp("raju")
Print(sum); disp("srinivas",35)
3.Keyword arguments:
The benefit of keyword arguments is that we can pass the argument in the
random order, which means the order of passing arguments doesn’t matter. Each
argument treated as the keyword. It will match argument names in the function
definition and function call.

def employee(id,name,age):

print('Employee Id:',id,'\nEmployee',name,'\nEmployee Age:',age)

employee(age=30,id=1,name= 'Srinivas‘)
employee(id=1,age=30,name='RAJU')
employee(name='RAVI',age=30,id=1)
4. Variable-length arguments:
Some times we are not sure about numbers of argument that can be passed
to a function, for such scenario, we use variable-length arguments.
There are two types of variable-length argument in a function:

 *args (Non-Keyword argument)


 **kwargs (Keyword argument)

*args (Non-Keyword argument)


Python provides *args which allows to pass the variable number of argument in a
function.

We should use an asterisk ( * ) before the argument name to pass variable length
arguments. The arguments are passed as a tuple, and these passed arguments make
tuple inside the function with the same name as the argument excluding asterisk *.

def variable(*names):
for I in names:
print(I )
variable(‘ raju ', ‘ ravi', ‘ kishan', ' devid', 'mohan')
**kwarg arguments
We cannot pass the keyword argument using *args. Python provides
**kwargs; It allows us to pass variable-length of keyword argument to the function.
We must use the double-asterisk ** before the argument name to denote
this type of argument. The arguments are passed as a dictionary, and these
arguments make a dictionary inside the function with name same as the parameter
without double asterisk **.

For example:

def variable(**names):
for key, value in names . items():
print(key , value)
variable( first_ name = “raju ", last _ name=' ravi ', Age=25,Salary=34000)

You might also like