0% found this document useful (0 votes)
3 views11 pages

Python basics notes .2 new

The document provides an overview of Python basics, focusing on strings, lists, tuples, and dictionaries. It covers key concepts such as indexing, slicing, string functions, and list methods, along with examples for each. Additionally, it highlights the mutable nature of lists and dictionaries compared to the immutable nature of tuples.

Uploaded by

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

Python basics notes .2 new

The document provides an overview of Python basics, focusing on strings, lists, tuples, and dictionaries. It covers key concepts such as indexing, slicing, string functions, and list methods, along with examples for each. Additionally, it highlights the mutable nature of lists and dictionaries compared to the immutable nature of tuples.

Uploaded by

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

Python basics

strings
Strings in python are stored as individual character in continuous location with
two way indexing for each location.
INDEXING
Backward indexing -6 -5 -4 -3 -2 -1
S= H E L L O !
Forward indexing 0 1 2 3 4 5

>>>L= ”PYTHON”

>>>L[0]
>>>P
>>>L[-2]
>>>O

Note – string[::-1] is an easy way to reverse the string


Item assignment
>>>Name=”krishna”
>>>Name [o]=” A”
#Error : str object does not support item assignment.

Traversing a string :
Traversing refers to iterating through a element of a string one
character at a time .
Code=”powerful”
for c in Code :
print (c,”~”end=””)
o/p:
p~o~w~e~r~f~u~l~
String Operators
Concatenation (+) Replication (*) Membership (in,not in)
>>>s1=”power” >>>3*”hi” >>>S=”hello”
>>>s2=”ful” >>>”hihihi” >>>“o” in S
>>>s1+s2 >>>True
>>>”powerful”

>>>s=”2” >>>7*”7” >>>str=”python”


>>>s1=”5” >>>”7777777” >>>”z”not in str
>>>s+s1 >>>True
>>>”25”

String slicing
• String slice refers to part of a string containing some continues
characters from the string.
• For index n,s[:n]+s[n:] will give you the original string s
• String [::-1] is an easy way to reverse the string
string functions

f.no Function syntax examples


1 len(<str>) >>>len(”hello”)
>>>5
2 <str>.capitalize() >>>”i love india”.capitalize()
>>>”I love india”
3 <str>.islower() >>>”hello”.islower()
>>>True
4 <str>.isupper() >>>”HELLO”.isupper()
>>>True
5 <str>.isdigit() >>>”12345”.isdigit()
>>>True
6 <str>.upper() >>>”python”.upper()
>>>”PYTHON”
7 <str>.lower() >>>”pyTHOn”.lower)
>>>”python”
8 <str>.swapcase() >>>”wElCOme”.swapcase()
>>>”WelcoMe”
9 <str>.find(sub ,start,end) >>>”green
revolution”.find(“green”)
>>>0
“green
revolution”.find(”green”,1,16)
>>>-1
10 <str>.index(<character>) >>>”hello world”.index(“w”))
>>>6
11 <str>.isalnum() >>>”123abc”.isalnum()
>>>True
12 <str>.isalpha() >>>”good”.isalpha()
>>>True
13 >>>”hello”.replace(“e”,”a”)
<str>.replace(old,new) >>>hallo
14 <str>.count(sub,[start,stop] >>>”dhanajayan”.count(“a”,0,8)
>>>4
15 <str>.title() >>>”my name is serious
“.tittle()
>>>”My Name Is Serious”
16 <str>.startswith() >>>”computer”.startswith(“c”)
>>>True
>>>”computer”.startswith(“C”)
>>>False
17 <str>.endswith() >>>”csc”.endswith(“c”)
>>>True
>>>”csc”.endswith(“s”)
>>>False
18 <str>join(sequence) >>>”ABCDE”.join(“*”)
>>>”A*B*C*D*E
19 <str>.isspace() >>>“ string”.isspace()
>>>True
20 <str>.split() >>>”python is easy “.split()
Or >>>[“python”,”is”,”easy”]
<str>.split([chars]) >>>”apple”.split(“p”)
>>>[“a”,””,”le”]
21 <str>.istitle() >>>”All Learn Python”.istitle()
>>>True
22 <str>.rstrip () or >>>” python ”.rstrip()
<str>.rstip([chars]) >>>” python”
>>>”python”.rstrip(“n”)
>>>”pytho”
23 <str>.lstrip() or >>>” global warming”.lstrip()
<str>.lstrip([optional]) >>>”global warming”
>>>”global
warming”.lstrip(“gl”)
>>>”obal warming”
24 <str>.strip() >>>” global warming ”.strip()
>>>”global warming”
25 <str>.partition(sep) >>>”Hard work
pays”.partition(“work”)
>>>(“hard”,”work”,’pays”)
26 ord() >>>ord(“a”)
>>>97
27 chr() >>>chr(65)
>>>”A”

Unpacking a string
>>>s=”string”
>>>x1,x2,x3,x4,x5,x6=s
>>>lst=list(s)
>>>tup=tuple(s)
>>>s
“string”
>>>x1,x2,x3,x4,x5,x6
(“s”,”t”,”r”,”i”,”n”,”g”)
>>>lst
[“s”,”t”,”r”,”I”,”n”,”g”]
>>>tup
(“s”,”t”,”r”,”i”,”n”,”g”)

Lists
like strings, lists are a sequence of values. A list is a data type that can
be used to store any type and number of variables and information.
A list in python is formed by enclosing the values inside square
brackets []. Unlike strings , lists are mutable data type.
List slicing
List[start:stop:step]
l=
-9 -8 -7 -6 -5 -4 -3 -2 -1
100 200 300 400 500 600 700 800 900
0 1 2 3 4 5 6 7 8

>>>l[5:]
[600,700,800,900]
>>>l[-9:-5]
[100,200,300,400]
>>>l[::-1]
[900,800,700,600,500,400,300,200,100]
Creating a nested list
L=[1,2,3,”abc”,[“c”,”s”,”c”],(2,3,6)]
>>>l[2:3]
[3]
>>>l[4][1]
“s”
Built in list functions and methods
Function Description Example
len(list) Returns the total L=[1,2,34,5]
length of the list len(L)
4
max (list) Returns the item max(L)
with maximum value 34
in the list
min(list) Returns the item min(L)
minimum value in 1
the list
list(seq) Converts a sequence A=1,2,3,4,”dj”
into list list(A)
[1,2,3,4,”dj”]
sum(list) Sums up all the sum(L)
numeric values 42
present in the list
Method Example
append(item) >>>Lst=[1,2,3]
>>>print(Lst.append(4))
[1,2,3,4]
extend(item) >>>a=[12,23,34]
>>>Lst.extend(a)
>>>print(Lst)
>>>[1,2,3,4,12,23,34]
index (item) >>>print(Lst.index(1))
>>>0
insert(index,item) >>>Lst.insert(3,4)
>>>print(Lst)
>>>[1,2,3,4]
sort() >>>print(Lst.sort())
>>>[4,3,2,1]
remove(item) >>>l=[1,11,2,22,1,4]
>>>print(l.remove(1))
>>>l
>>>[11,2,22,1,4]
reverse() >>>print(l.reverse())
>>>[1,2,4,11,22]
count(element) >>>=k[1,2,3,4,1,2,3,4,1,1]
>>>print(k.count(1))
>>>4

Tuple
The tuple is a sequence of immutable Python objects.
Iterating through a tuple
Elements of tuple can be accessed sequentially using loop.
Example:
Traversing in Tuple:
Tup=(5,11,22)
for i in range (0,len(Tup)):
print(Tup[i])
o/p:
5
11
22
Tuple operation Explanation Example
Creating a Tuple New tuple can be T=()
created by enclosing T=(3,3,’a’,[1,2])
in simple T=(5,)
parenthesis
Accessing tuple each item is stored t= (1,2,’p’,’*’,50.5)
elements individually and print(t[2])
accessed through o/p: p
indexing
Slicing in a tuple slicing can be done t= (1,2,’p’,’*’,50.5)
using : (colon) print(t[1:2])
operator. Slicing o/p: 2
uses indexing, either
positive or negative.
Concatenating 2 joining the tuple t= (1,2,’p’,’*’,50.5)
tuples elements with t1=(3,)
another tuple using t2=t+t1
+ operator print(t2)
o/p:
(1,2,’p’,’*’,50.5,3)
Repeating elements repeat the elements t=(‘Good’)*2
of a tuple of the tuple by a print(t)
specified number of o/p: GoodGood
times. They are not
copied but are
referenced multiple
times.
Using membership these operators are t= (1,2,’p’,’*’,50.5)
operators used to check 1 in t
whether a value o/p: True
exists in the tuple or t= (1,2,’p’,’*’,50.5)
not. ‘z’ not in t
o/p: True
Traversing a tuple
using loop

Built in functions in tuples:


Function Explanation Example
len() Returns the length t= (1,2,’p’,’*’,50.5)
of the tuple print(len(t))
o/p: 5
tuple() The tuple function is T=tuple()
also called a Print(T)
constructor. It is o/p: ()
used to create L=[1,2,’anu’]
empty tuple or with X=tuple(L)
values. Print(X)
o/p: X=(1,2,’anu’)

count() This function returns t= (1,2,2,22,222)


the total number of print(count(2))
times an element o/p: 2
has appeared in a
tuple.
Index() This function returns t= (1,2,’p’,’*’,50.5)
the index of the first print(index(50))
occurrence of a o/p: Error
given element in the t= (1,2,’p’,’*’,50.5)
tuple otherwise print(index(50.5))
error. o/p: 4
max() This function returns t= (1,2,’p’,’*’,50.5)
the maximum value print(max(t))
in a tuple. o/p: error
min() This function returns tup=(1,2,3,-1)
the minimum value print(min(t))
in a tuple. o/p: -1
sum() This function returns X=(1.1,2,2.5,4.5,9)
the total value of all sum(X)
the items in a tuple. o/p: 19.1

sorted() Sorts in ascending to t=(8,-6)


descending order print(sorted(t))
[-6, 8]

Dictionary:
Dictionary is a data type in python. It is an unordered collection of
items (order may be changed after defining). Each item has a key :
value pair.
Dictionary is a mutable data type.(the values can be added,
removed, and changed at any time).
*Note: The keys in the dictionaries are immutable.
D={1:’a’,2:’e’}

Dictionary Explanation Example


operations
Creating a dictionary The dict() function is D=dict()
used to create a print(D)
dictionary with or {}
without key-value
pair

You might also like