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

Data Analysis With Python, String, List, Tuples, Dictionary

This document provides information about strings and lists in Python. It discusses how to define and manipulate strings and lists through indexing, slicing, concatenation, length calculation, iteration, and various string/list methods. Some key string operations covered are comparison, joining, finding length. For lists, topics covered include accessing elements, adding/removing items using methods like append, insert, remove, pop, as well as slicing and negative indexing.

Uploaded by

Muskan Zahra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Data Analysis With Python, String, List, Tuples, Dictionary

This document provides information about strings and lists in Python. It discusses how to define and manipulate strings and lists through indexing, slicing, concatenation, length calculation, iteration, and various string/list methods. Some key string operations covered are comparison, joining, finding length. For lists, topics covered include accessing elements, adding/removing items using methods like append, insert, remove, pop, as well as slicing and negative indexing.

Uploaded by

Muskan Zahra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Data Analysis and Visualization Lab (CS-352 )

Topics String, List, Tuple, Dictionary, File

Lab 01 – Lab Manual

Strings
 A string is a sequence of characters.
For example, "hello" is a string containing a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

# create a string using double quotes


string1 = "Python programming"
print(string1)

OUTPUT

Python programming

 Accessing String Characters


1. Indexing:

# access 4th index element


print(string1[4])

OUTPUT

2. Negative Indexing:

# access 3rd last element


print(string1[-3])

OUTPUT

3. Slicing:

# access character from 1st index to 4th index


print(string1[1:5])

OUTPUT
ytho

4. Slicing with a jump:

# access character from 1st index to 10th index with a jump of 2


print(string1[1:10:2])

OUTPUT

yhnpo

 Python String Operations:


1. Compare Two Strings: We use the == operator to compare two strings. If two strings are equal, the operator
returns True. Otherwise, it returns False. For example,

str1 = "Hello, world!"


str2 = "Python Programming."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2)

# compare str1 and str3


print(str1 == str3)

OUTPUT

False
True

2. Join Two or More Strings: We can join (concatenate) two or more strings using the + operator.

str1 = "Hello"
str2 = "World"

# concatenate str1 and str2


print(str1 + str2)

OUTPUT

HelloWorld

3. Finding length of String: We can find the length of a string using len() function.

str1 = "Hello"

# find the length of string


print(len(str1)

OUTPUT

 Iterate Through a Python String:


We can iterate through a string using a for loop. For example,
greet="Hello"

# iterating through greet string


for letter in greet:
print(letter)

OUTPUT

H
e
l
l
o

 Methods of Python String:


str1="hello"
str2="PYTHON"

Function Description Usage Output


converts the first character to an print(str2.capitalize()) Python
capatilize() uppercase letter and others to
lowercase
returns a string after padding it print(str2.center(14,'*')) ****PYTHON****
center()
with the specified character
returns the number of occurrences print(str1.count('l')) 2
count()
of a substring in the given string. print(str1.count('l',0,3)) 1
returns True if a string ends with print(str1.endswith('o')) True
endswith()
the specified suffix. print(str1.endswith('o',1,3)) False
returns the index of first print(str2.find('O')) 4
find()
occurrence of substring print(str2.find('O',1,3)) -1
returns True if all characters in print(str2.isalnum()) True
isalnum()
the string are alphanumeric
returns True if all characters in print(str2.isalpha()) True
isalpha()
the string are alphabets
returns True if all characters in a print(str2.isdigit()) False
isdigit()
string are digits
isidentifier() returns True if the string is a print(str1.isidentifier()) True
valid identifier in Python
returns True if all alphabets in a print(str2.islower()) False
islower()
string are lowercase
returns True if there are only print(str2.isspace()) False
isspace() whitespace characters in the
string
returns True if the string is a print(str2.istitle()) False
istitle()
titlecased string
returns True if the string is a print(str2.isupper()) True
isupper()
upper case string
lower() converts the string to lowercase print(str2.lower()) python
returns a tuple containing the part print(str2.partition("t")) ('Py', 't', 'hon')
the before separator, argument
partition()
string and the part after the
separator.
replaces each matching print(str1.replace('o','ooo')) hellooo
replace() occurrence of a substring with
another string
splits a string at the specified print("BSCS-2020- ['BSCS', '2020',
split() separator and returns a list of Morning".split('-')) 'Morning']
substrings.
returns True if a string starts with print(str2.startswith('h')) False
startswith()
the specified substring print(str2.startswith('h',3,5)) True
returns a string with first letter of print(str1.title()) Hello
title()
each word capitalized
upper() converts the string to uppercase print(str1.upper()) HELLO

LIST
 Lists are used to store multiple data at once.
 For example: Suppose we need to record the ages of 5 students. Instead of creating 5 separate variables, we can
simply create a list:

age= [17, 18, 15, 19, 14 ]


print(age)
OUTPUT

[17, 18, 15, 19, 14 ]

 Access Python List Elements:


1. Indexing:
age= [17, 18, 15, 19, 14 ]

for i in range(len(age)):
print(age[i], end=" ")

OUTPUT

17 18 15 19 14

2. Negative Indexing:
age= [17, 18, 15, 19, 14]
print(age[-3])

OUTPUT

15

3. Slicing
age= [17, 18, 15, 19, 14]
print(age[2:4])

OUTPUT

[15, 19]
 Add Elements to a Python List:
1. Using append(): The append() method adds an item at the end of the list.
age= [17, 18, 15, 19, 14]
age.append(90)
print(age)

OUTPUT

[17, 18, 15, 19, 14, 90]

2. Using extend(): It adds all items of one list to another.


prime_numbers = [2, 3, 5]
print("List1:", prime_numbers)

even_numbers = [4, 6, 8]
print("List2:", even_numbers)
# join two lists
prime_numbers.extend(even_numbers)

print("List after append:", prime_numbers)

OUTPUT

List1: [2, 3, 5]
List2: [4, 6, 8]
List after append: [2, 3, 5, 4, 6, 8]

3. Using insert(): The insert() method inserts an element to the list at the specified index.
# create a list of vowels
vowel = ['a', 'e', 'i', 'u']

# 'o' is inserted at index 3 (4th position)


vowel.insert(3, 'o')

print('List:', vowel)

OUTPUT

List: ['a', 'e', 'i', 'o', 'u']

 Remove an Item From a List:

1. Using del: We can use the del statement to remove one or more items from a list.
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']

# deleting the second item


del languages[1]
print(languages)

# delete first two items


del languages[0 : 2] # ['C', 'Java', 'Rust']
print(languages)

OUTPUT

['Python', 'C++', 'C', 'Java', 'Rust', 'R']


['C', 'Java', 'Rust', 'R']

2. Using remove(): We can also use the remove() method to delete a list item.
languages = ['Python', 'Swift', 'C++', 'C', 'Java', 'Rust', 'R']
# remove 'Python' from the list
languages.remove('Python')

print(languages)

OUTPUT

['Swift', 'C++', 'C', 'Java', 'Rust', 'R']

3. Using pop(): The pop() method removes the item at the given index from the list and returns the removed
item.
# create a list of prime numbers
prime_numbers = [2, 3, 5, 7]

# remove the element at index 2


removed_element = prime_numbers.pop(2)

print('Removed Element:', removed_element)


print('Updated List:', prime_numbers)

OUTPUT

Removed Element: 5
Updated List: [2, 3, 7]

4. Using clear():The clear() method removes all items from the list.
prime_numbers = [2, 3, 5, 7, 9, 11]

# remove all elements


prime_numbers.clear()

# Updated prime_numbers List


print('List after clear():', prime_numbers)

OUTPUT

List after clear(): []


 Python List Methods:

Function Description Usage Output


returns the index of animals = ['cat', 'dog', 'rabbit', 1
index() the first matched item 'horse']
index = animals.index('dog')
returns the count of numbers = [2, 3, 5, 2, 11, 2, 7] 3
count() the specified item in count = numbers.count(2)
the list
sort() sort the list in prime_numbers = [11, 3, 7, 5, 2] [2, 3, 5, 7, 11]
ascending/descending prime_numbers.sort()
order
reverses the item of prime_numbers = [2, 3, 5, 7] [7, 5, 3, 2]
reverse()
the list prime_numbers.reverse()
returns a shallow copy prime_numbers = [2, 3, 5] [2, 3, 5]
copy() of the list numbers =
prime_numbers.copy()

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 whereas we can change the elements of a list.

 Creating a Tuple:

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
print(my_tuple)

# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)

OUTPUT

()
(1, 2, 3)
(1, 'Hello', 3.4)
('mouse', [8, 4, 6], (1, 2, 3))

 Accessing a Tuple:
Like a list, tuples can be accessed using:
1. Index
2. Negative Index
3. Slicing
 Python Tuple Methods:

Function Description Usage Output


returns the index of the first my_tuple = ('a', 'p', 'p', 'l', 'e',) 3
index()
matched item print(my_tuple.index('l'))
returns the count of the my_tuple = ('a', 'p', 'p', 'l', 'e',) 2
count()
specified item in the tuple print(my_tuple.count('p'))

DICTIONARY

 Python dictionary is an ordered collection of items. It stores elements in key/value pairs. Here, keys are unique
identifiers that are associated with each value.
 Example:
If we want to store information about countries and their capitals, we can create a dictionary with country names
as keys and capitals as values.

 Create a dictionary:
capital_city = {"Nepal": "Kathmandu", "Italy": "Rome", "England": "London"}
print(capital_city)

OUTPUT

{'Nepal': 'Kathmandu', 'Italy': 'Rome', 'England': 'London'}

 Accessing Elements from Dictionary


student_id = {111: "Ali", 112: "Fatima", 113: "Amna"}
print(student_id[112])
print(student_id[111])

OUTPUT

Fatima
Ali
 Add Elements to a Dictionary:
capital_city = {"Nepal": "Kathmandu", "England": "London"}
print("Initial Dictionary: ",capital_city)

capital_city["Japan"] = "Tokyo"

print("Updated Dictionary: ",capital_city)

OUTPUT

Initial Dictionary: {'Nepal': 'Kathmandu', 'England': 'London'}


Updated Dictionary: {'Nepal': 'Kathmandu', 'England': 'London', 'Japan': 'Tokyo'}

 Change Value of Dictionary:


student_id = {111: "Ali", 112: "Fatima", 113: "Amna"}
print("Initial Dictionary: ", student_id)

student_id[112] = "Zahra"

print("Updated Dictionary: ", student_id)

OUTPUT

Initial Dictionary: {111: 'Ali', 112: 'Fatima', 113: 'Amna'}


Updated Dictionary: {111: 'Ali', 112: 'Zahra', 113: 'Amna'}

 Removing elements from Dictionary:


student_id = {111: "Ali", 112: "Fatima", 113: "Amna"}
print("Initial Dictionary: ", student_id)

del student_id[111]

print("Updated Dictionary: ", student_id)

OUTPUT

Initial Dictionary: {111: 'Ali', 112: 'Fatima', 113: 'Amna'}


Updated Dictionary: {112: 'Fatima', 113: 'Amna'}

 Python Dictionary Methods:

Function Description Usage Output


Return the number of items in languages = ['Python', 'Java', 3
len() the dictionary. 'JavaScript']
length = len(languages)
Return a new sorted list of numbers = [4, 2, 12, 8] [2, 4, 8, 12]
sorted() keys in the dictionary. sorted_numbers =
sorted(numbers)
Removes all items from the numbers = {1: "one", 2: "two"} {}
clear()
dictionary numbers.clear()
Returns a new object of the numbers = {1: 'one', 2: 'two', 3: dict_keys([1, 2, 3])
dictionary's keys 'three'}
keys()
dictionaryKeys =
numbers.keys()
Returns a new object of the marks = {'Physics':67, dict_values([67, 87])
values() dictionary's values 'Maths':87}
print(marks.values())
Returns a view object that marks = {'Physics':67, dict_items([('Physics', 67),
items() displays a list of dictionary's 'Maths':87} ('Maths', 87)])
(key, value) tuple pairs. print(marks.items())
Returns the value for the marks = {'Physics':67, 67
get() specified key if the key is in 'Maths':87}
the dictionary. print(marks.get('Physics'))
removes and returns an marks = { 'Physics': 67, 72
element from a dictionary 'Chemistry': 72, 'Math': 89 }
pop()
having the given key. element =
marks.pop('Chemistry')

FILES
 A file is a container in computer storage devices used for storing data.
 When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so
that the resources that are tied with the file are freed.
 Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file

 Reading Files in Python:


In Python, we use the open() method to open files.

# open a file with open("test.txt", "r") as file1:


file1 = open("test.txt", "r") read_content = file1.read()
print(read_content)
# read the file
read_content = file1.read()
print(read_content)
# close the file
file1.close()

OUTPUT

This is a test file.


Hello from the test file.

Different Modes to Open a File in Python

Mode Description
r Open a file for reading. (default)
w Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x Open a file for exclusive creation. If the file already exists, the operation fails.
a Open a file for appending at the end of the file without truncating it. Creates a new file if it does not
exist.
t Open in text mode. (default)
b Open in binary mode.
+ Open a file for updating (reading and writing)

 Writing to Files in Python:


In order to write into a file in Python, we need to open it in write mode by passing "w" inside open() as a second
argument.
with open(test2.txt', 'w') as file2:

# write contents to the test2.txt file


file2.write('Programming is Fun.')
fil2.write('Data Analysis and Visualization')

OUTPUT

THE END

You might also like