0% found this document useful (0 votes)
8 views8 pages

Chapter-2 DataStructures in Python

The document provides an overview of data structures in Python, including strings, lists, tuples, dictionaries, sets, and arrays. It includes examples of basic operations such as accessing elements, slicing, concatenation, and various methods for manipulating these data structures. Additionally, it contains practice programs for further understanding of lists and tuples.

Uploaded by

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

Chapter-2 DataStructures in Python

The document provides an overview of data structures in Python, including strings, lists, tuples, dictionaries, sets, and arrays. It includes examples of basic operations such as accessing elements, slicing, concatenation, and various methods for manipulating these data structures. Additionally, it contains practice programs for further understanding of lists and tuples.

Uploaded by

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

UNIT-2

Data Structures In Python

1. String

Program 1 :

name = "Python"

print(name[0]) # Accessing character

print(name[1:4]) # Slicing

print(len(name)) # Length

print(name.upper()) # Uppercase

print(name + " Rocks") # Concatenation

2.List and Tuples

# List

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

fruits.append("orange")

print(fruits)

# Tuple

days = ("Mon", "Tue", "Wed")

print(days[1])

3. student = {"name": "Alice", "age": 21}

student["course"] = "Python"

print(student)

print(student.keys())

1
# Convert lists to dict

keys = ["name", "age"]

values = ["Bob", 22]

data = dict(zip(keys, values))

print(data)

5.Sets

roll_numbers = {101, 102, 103}

roll_numbers.add(104)

print(roll_numbers)

6.Array

from array import array

marks = array('i', [50, 60, 70])

marks.append(80)

print(marks)

# 2D array using numpy

import numpy as np

matrix = np.array([[1, 2], [3, 4]])

print(matrix)

2
30/7/25

Creating Strings in Python


# Examples of string creation

str1 = 'Hello'

str2 = "World"

str3 = '''This is

a multiline string'''

print(str1)

print(str2)

print(str3)

Basic String Operations


1) Accessing Characters (Indexing)
name = "Python"
print(name[0]) # P
print(name[2]) # t

2) Slicing Strings
text = "Programming"
print(text[0:4]) # Prog
print(text[4:]) # ramming

3) Concatenation (Joining Strings)


first = "Data"
second = "Science"
result = first + " " + second
print(result) # Data Scienc
4) Repetition
word = "Hi"
print(word * 3) # HiHiHi

3
5) String Length
msg = "Python"
print(len(msg)) # 6

6) greet = "hello world"


print(greet.upper()) # HELLO WORLD
print(greet.capitalize()) # Hello world
print(greet.replace("world", "Python")) # hello Python
print(greet.split()) # ['hello', 'world']

7) Looping Through a String


word = "Code"
for char in word
print(char)
8) Program to Compare Two Strings
str1 = "Apple"
str2 = "apple"
if str1 == str2:
print("Both strings are equal.")
else:
print("Strings are not equal.")

9) Program to Count Vowels in a String


text = "Engineering"
vowels = "aeiouAEIOU"
count = 0

for ch in text:
if ch in vowels:
count += 1

print("Number of vowels:", count)

4
10) Program to Reverse a String

text = "Python"

reversed_text = text[::-1]

print("Original:", text)

print("Reversed:", reversed_text) # nohtyP

11. Program to Check if a Word Exists in String


sentence = "Learning Python is fun"
if "Python" in sentence:
print("Yes, 'Python' is in the sentence.")
else:
print("No, it's not there.")

12. Program Using String Methods


msg = "hello world"

print("Uppercase:", msg.upper()) # HELLO WORLD


print("Capitalized:", msg.capitalize()) # Hello world
print("Replace 'world' with 'Python':", msg.replace("world", "Python")) #
hello Python
print("Split string:", msg.split()) # ['hello', 'world']

Practice Programs – List and Tuples

5
1. Create a list and print all elements

fruits = ["apple", "banana", "mango", "orange"]

print("Fruit List:", fruits)

2. Add and remove elements from a list

numbers = [10, 20, 30]

numbers.append(40)

numbers.remove(20)

print("Updated list:", numbers)

3. Find the length of a list

names = ["John", "Alice", "Bob"]

print("Total names:", len(names))

4. Sort a list in ascending and descending order

marks = [55, 78, 90, 67, 45]

marks.sort()

print("Ascending:", marks)

marks.sort(reverse=True)

print("Descending:", marks)

5. Find the maximum, minimum, and sum of list elements


scores = [90, 85, 88, 76]

print("Max:", max(scores))

print("Min:", min(scores))

print("Sum:", sum(scores))

6. Search for an element in a list


colors = ["red", "blue", "green"]
if "green" in colors:
print("Green is present!")
else:
print("Green is not in the list.")

7. Use a for loop to print each element in a list

6
cities = ["Delhi", "Mumbai", "Chennai"]

for city in cities:

print(city)

8. Reverse a list

nums = [1, 2, 3, 4, 5]

nums.reverse()

print("Reversed List:", nums)

Practice Programs – Tuples

1. Create a tuple and print elements

student = ("Alice", 21, "CSE")

print("Student Info:", student)

2. Access elements using index

animals = ("cat", "dog", "elephant")

print("First animal:", animals[0])

3. Count occurrences of an element in a tuple

nums = (1, 2, 3, 1, 4, 1)

print("Count of 1:", nums.count(1))

4. Convert tuple to list and list to tuple


# Tuple to list
tup = (1, 2, 3)
lst = list(tup)
print("List:", lst)

# List to tuple
lst2 = [4, 5, 6]
tup2 = tuple(lst2)
print("Tuple:", tup2)

5. Iterate through a tuple using a loop

subjects = ("Math", "Physics", "Chemistry")

for sub in subjects:

print(sub)

7
6. Find the length and index of elements in a tuple
alphabets = ("a", "b", "c", "d")
print("Length:", len(alphabets))
print("Index of 'c':", alphabets.index("c"))

You might also like