Unit IV String,Lists,Tuple&Dictionaries | Cse 108 Python Programming |B.tech cse

 


1. String as a Compound Data Type

  • A string in Python is a sequence of characters, and strings can be thought of as a compound data type because they consist of multiple elements (characters).
  • Strings in Python are immutable, meaning their contents cannot be changed after creation. However, you can create new strings by manipulating the original string.

Example:

my_string = "Hello"

Here, "Hello" is a string composed of 5 characters: H, e, l, l, o.

Length of a String (len())

  • You can use the len() function to find the number of characters in a string (its length).

Syntax:


len(string)

Example:

my_string = "Hello" print(len(my_string)) # Output: 5

String Traversal

  • String traversal means iterating through the characters of a string, one by one, using loops (e.g., for loop).

Example:

my_string = "Hello"
for char in my_string: print(char)

Output:

H e l l o
  • This example iterates over each character in the string "Hello" and prints it.

String Slicing

  • String slicing allows you to extract a substring from a string by specifying a range of indices. The syntax for string slicing is:

Syntax:

string[start:end:step]
  • start: The index where the slice starts (inclusive).
  • end: The index where the slice ends (exclusive).
  • step: (Optional) The step or stride between characters.

Example:

my_string = "Hello, World!" print(my_string[0:5]) # Output: Hello print(my_string[7:]) # Output: World! print(my_string[:5]) # Output: Hello print(my_string[::2]) # Output: Hlo ol!

Here:

  • my_string[0:5] returns characters from index 0 to 4 (i.e., "Hello").
  • my_string[7:] returns everything from index 7 to the end (i.e., "World!").
  • my_string[:5] returns the first 5 characters (i.e., "Hello").
  • my_string[::2] returns every second character (i.e., "Hlo ol!").

 String Comparison

  • You can compare two strings using relational operators like ==, !=, <, >, <=, and >=. This compares the strings lexicographically (i.e., based on their alphabetical order).

Example:

string1 = "apple" string2 = "banana" print(string1 == string2) # Output: False print(string1 != string2) # Output: True print(string1 < string2) # Output: True (because 'a' < 'b') print(string1 > string2) # Output: False

Find Function

  • The find() method is used to search for a substring within a string. It returns the lowest index at which the substring is found. If the substring is not found, it returns -1.

Syntax:

string.find(substring)

Example:

my_string = "Hello, World!" print(my_string.find("World")) # Output: 7 print(my_string.find("Python")) # Output: -1

Looping Through a String

  • You can loop over a string in various ways, including using for loops or while loops. The for loop iterates through each character of the string.

Example (using for loop):

my_string = "Python" for char in my_string: print(char)

Example (using while loop):

my_string = "Python" i = 0 while i < len(my_string): print(my_string[i]) i += 1

Counting Substrings in a String

  • The count() method counts how many times a substring appears in the string.

Syntax:

string.count(substring)

Example:

my_string = "hello, hello, hello" print(my_string.count("hello")) # Output: 3


Built-in String Functions in Python

Python provides a wide range of built-in string functions that allow you to manipulate and work with text efficiently. Below is a table listing some of the most commonly used string functions in Python along with their descriptions and examples.

String Function Description Example
len() Returns the length of the string (number of characters).
my_string = "Hello, Python!"
print(len(my_string)) # Output: 14
capitalize() Capitalizes the first character of the string and makes all other characters lowercase.
my_string = "hello, python!"
print(my_string.capitalize()) # Output: 'Hello, python!'
casefold() Returns a case-insensitive version of the string (useful for case-insensitive comparisons).
my_string = "HELLO, PYTHON!"
print(my_string.casefold()) # Output: 'hello, python!'
lower() Converts all characters in the string to lowercase.
my_string = "HELLO, PYTHON!"
print(my_string.lower()) # Output: 'hello, python!'
upper() Converts all characters in the string to uppercase.
my_string = "hello, python!"
print(my_string.upper()) # Output: 'HELLO, PYTHON!'
swapcase() Swaps the case of all characters in the string (upper to lower and vice versa).
my_string = "Hello, Python!"
print(my_string.swapcase()) # Output: 'hELLO, pYTHON!'
strip() Removes leading and trailing whitespace characters from the string.
my_string = "   Hello, Python!   "
print(my_string.strip()) # Output: 'Hello, Python!'
lstrip() Removes leading (left) whitespace characters from the string.
my_string = "   Hello, Python!"
print(my_string.lstrip()) # Output: 'Hello, Python!'
rstrip() Removes trailing (right) whitespace characters from the string.
my_string = "Hello, Python!   "
print(my_string.rstrip()) # Output: 'Hello, Python!'
replace() Replaces occurrences of a substring with another substring.
my_string = "Hello, Python!"
print(my_string.replace("Python", "World")) # Output: 'Hello, World!'
split() Splits the string into a list of substrings based on a delimiter (default is whitespace).
my_string = "Hello, Python!"
print(my_string.split()) # Output: ['Hello,', 'Python!']
join() Joins elements of a list into a string, using a specified delimiter.
my_list = ['Hello', 'Python', 'World']
print(" ".join(my_list)) # Output: 'Hello Python World'
find() Returns the index of the first occurrence of a substring. Returns -1 if not found.
my_string = "Hello, Python!"
print(my_string.find("Python")) # Output: 7
print(my_string.find("Java")) # Output: -1
startswith() Returns True if the string starts with the specified substring.
my_string = "Hello, Python!"
print(my_string.startswith("Hello")) # Output: True
print(my_string.startswith("Python")) # Output: False
endswith() Returns True if the string ends with the specified substring.
my_string = "Hello, Python!"
print(my_string.endswith("Python!")) # Output: True
print(my_string.endswith("World!")) # Output: False
isdigit() Returns True if all characters in the string are digits.
my_string = "12345"
print(my_string.isdigit()) # Output: True
my_string = "123a45"
print(my_string.isdigit()) # Output: False
isalpha() Returns True if all characters in the string are alphabetic.
my_string = "Hello"
print(my_string.isalpha()) # Output: True
my_string = "Hello123"
print(my_string.isalpha()) # Output: False
format() Inserts variables or values into placeholders in a string.
name = "Python"
version = 3.10
print("Welcome to {}, version {}".format(name, version)) # Output: 'Welcome to Python, version 3.10'

These string methods are useful for text manipulation, searching, formatting, and performing various operations in Python. Try them out to improve your string handling skills!

Lists in Python

Lists are one of the most commonly used data structures in Python. They are mutable (can be modified), ordered (elements have a defined order), and can contain elements of different data types.

Here’s a breakdown of key concepts related to lists in Python:

Declaring a List in Python

A list in Python is declared by placing the elements inside square brackets []. The elements can be of different data types, including integers, strings, floats, and even other lists.

Example 1: Declaring a List with Elements

# A list of integers my_list = [1, 2, 3, 4, 5] # A list of strings fruits = ["apple", "banana", "cherry"] # A mixed-type list mixed_list = [1, "apple", 3.14, True]

Here:

  • my_list is a list of integers.
  • fruits is a list of strings.
  • mixed_list is a list containing elements of different data types.

Creating an Empty List

To create an empty list (a list with no elements), you can simply use empty square brackets [] or use the list() constructor.

Example 2: Creating an Empty List

# Using square brackets empty_list = [] # Using the list() constructor another_empty_list = list()

Both methods create an empty list. You can add elements to these lists later by using methods such as append(), extend(), or direct index assignment.

Example 3: Adding Elements to an Empty List

empty_list = [] empty_list.append(10) # Adds 10 to the list empty_list.append("hello") # Adds "hello" to the list print(empty_list) # Output: [10, 'hello']

1. List Values:

A list in Python can store multiple values (elements) within a single variable. The values can be of different data types such as strings, numbers, or even other lists.

my_list = [10, "apple", 3.14, True]

2. Length of a List:

The len() function is used to get the number of elements in a list.

my_list = [1, 2, 3, 4, 5] print(len(my_list)) # Output: 5

3. Membership:

You can check if an item exists in a list using the in keyword. It returns True if the item is found in the list and False otherwise.

my_list = [1, 2, 3, 4, 5] print(3 in my_list) # Output: True print(6 in my_list) # Output: False

4. List Operations:

  • Concatenation: You can concatenate two or more lists using the + operator.
list1 = [1, 2, 3] list2 = [4, 5, 6] combined_list = list1 + list2 print(combined_list) # Output: [1, 2, 3, 4, 5, 6]
  • Repetition: You can repeat a list using the * operator.
my_list = [1, 2] repeated_list = my_list * 3 print(repeated_list) # Output: [1, 2, 1, 2, 1, 2]

5. List Slicing:

List slicing allows you to extract a portion of the list. The syntax for slicing is list[start:end:step].

my_list = [10, 20, 30, 40, 50] print(my_list[1:4]) # Output: [20, 30, 40] print(my_list[:3]) # Output: [10, 20, 30] print(my_list[::2]) # Output: [10, 30, 50]

6. List Deletion:

You can delete elements from a list using the del statement or the remove() and pop() methods.

  • Using del: Deletes an element by index.
my_list = [10, 20, 30, 40] del my_list[2] # Removes the element at index 2 print(my_list) # Output: [10, 20, 40]
  • Using remove(): Removes the first occurrence of a specified value.
my_list = [10, 20, 30, 20] my_list.remove(20) # Removes the first occurrence of 20 print(my_list) # Output: [10, 30, 20]
  • Using pop(): Removes an element by index and returns it.
my_list = [10, 20, 30, 40] removed_item = my_list.pop(1) # Removes and returns the element at index 1 print(removed_item) # Output: 20

print(my_list) # Output: [10, 30, 40]
7. Accessing List Elements:

You can access list elements using their index. Remember that Python uses zero-based indexing.

my_list = ["apple", "banana", "cherry"] print(my_list[0]) # Output: 'apple' print(my_list[-1]) # Output: 'cherry' (last element)

8. List and for Loops:

You can loop through a list using a for loop to access each element.

my_list = [1, 2, 3, 4, 5] for item in my_list: print(item)

9. List Parameters:

Lists can be passed as arguments to functions. You can also return a list from a function.

def square_elements(lst): return [x ** 2 for x in lst] numbers = [1, 2, 3] squared_numbers = square_elements(numbers) print(squared_numbers) # Output: [1, 4, 9]

10. Nested Lists:

Lists can contain other lists as elements, allowing you to create multidimensional data structures (like matrices).

nested_list = [[1, 2, 3], [4, 5, 6]] print(nested_list[0]) # Output: [1, 2, 3] print(nested_list[1][2]) # Output: 6 (element at index 2 of the second list

Built-in List Functions in Python

Below is a table listing some of the most commonly used list functions in Python along with their descriptions and examples.

List Function Description Example
append() Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
extend() Appends all elements of an iterable (e.g., list) to the end of the list.
my_list = [1, 2, 3]
my_list.extend([4, 5])
print(my_list) # Output: [1, 2, 3, 4, 5]
insert() Inserts an element at a specified index.
my_list = [1, 2, 3]
my_list.insert(1, "apple")
print(my_list) # Output: [1, 'apple', 2, 3]
remove() Removes the first occurrence of a specified value.
my_list = [1, 2, 3, 4]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4]
pop() Removes and returns the element at a specified index (default is the last element).
my_list = [1, 2, 3]
popped_item = my_list.pop(1)
print(popped_item) # Output: 2
print(my_list) # Output: [1, 3]
sort() Sorts the list in ascending order. Can take `reverse=True` for descending order.
my_list = [3, 1, 2]
my_list.sort()
print(my_list) # Output: [1, 2, 3]
reverse() Reverses the elements of the list in place.
my_list = [1, 2, 3]
my_list.reverse()
print(my_list) # Output: [3, 2, 1]
count() Returns the number of occurrences of a specified value in the list.
my_list = [1, 2, 2, 3, 2]
print(my_list.count(2)) # Output: 3
index() Returns the index of the first occurrence of a specified value.
my_list = [1, 2, 3]
print(my_list.index(2)) # Output: 1
clear() Removes all elements from the list.
my_list = [1, 2, 3]
my_list.clear()
print(my_list) # Output: []
list() Creates a new list from an iterable (e.g., a string, tuple, or set).
my_string = "hello"
my_list = list(my_string)
print(my_list) # Output: ['h', 'e', 'l', 'l', 'o']
Creating an Empty List Creates an empty list.
empty_list = []
another_empty_list = list()
print(empty_list) # Output: []
print(another_empty_list) # Output: []

These built-in functions help you manipulate lists in Python. Try them out and experiment with different operations!


Tuples in Python

1. Mutability

  • Tuples are immutable in Python, meaning once a tuple is created, its elements cannot be changed, added, or removed.
  • However, if a tuple contains mutable elements (like a list), those elements can be modified.

Example:

# Immutable tuple t = (1, 2, 3) # t[0] = 10 # This will raise a TypeError # Tuple with mutable elements t2 = ([1, 2], (3, 4)) t2[0][0] = 10 # This is allowed because the list inside is mutable print(t2) # Output: ([10, 2], (3, 4))

2. Tuple Assignment

Tuple assignment is a technique where you can assign values to multiple variables at once using a tuple.

Example:

# Tuple assignment x, y, z = (1, 2, 3) print(x, y, z) # Output: 1 2 3

3. Tuples as Return Values

Functions can return tuples, making it easy to return multiple values.

Example:

def get_coordinates():
return (10, 20) x, y = get_coordinates() print(x, y) # Output: 10 20

4. How to Declare Tuples

  • Single element tuple: A tuple with one element requires a comma to differentiate it from a regular value.
  • Empty tuple: Declared using ().

Examples:

# Single-element tuple t = (1,) # Note the comma print(type(t)) # Output: <class 'tuple'> # Empty tuple empty_tuple = () print(type(empty_tuple)) # Output: <class 'tuple'>
Tuple Built-in Functions

Tuple Built-in Functions

Function Description Example
len() Returns the length (number of elements) in the tuple. len((1, 2, 3)) → 3
min() Returns the smallest element in the tuple. min((1, 2, 3)) → 1
max() Returns the largest element in the tuple. max((1, 2, 3)) → 3
sum() Returns the sum of the elements in the tuple. sum((1, 2, 3)) → 6
tuple() Converts an iterable into a tuple. tuple([1, 2, 3]) → (1, 2, 3)


Dictionaries in Python

. Dictionary Operations and Methods

  • Dictionaries are mutable collections that store data as key-value pairs.
  • Common dictionary operations include adding, removing, and accessing elements.

1. How to Declare Dictionaries

  • Dictionary: You can declare a dictionary using curly braces {} with key-value pairs.
  • Empty Dictionary: An empty dictionary is created using {}.

Example:

# Declaring a dictionary with key-value pairs d = {'name': 'Alice', 'age': 25} # Declaring an empty dictionary empty_dict = {} print(type(empty_dict)) # Output: <class 'dict'>

2. Dictionary Operations and Methods

  • Dictionaries are mutable collections that store data as key-value pairs.
  • Common dictionary operations include adding, removing, and accessing elements.

Basic Operations:

# Creating a dictionary d = {'name': 'Alice', 'age': 25} # Adding or updating a key-value pair d['location'] = 'New York' # Adding d['age'] = 26 # Updating # Accessing values print(d['name']) # Output: Alice # Removing a key-value pair del d['age'] # Removes the key 'age' and its value # Getting keys and values print(d.keys()) # Output: dict_keys(['name', 'location']) print(d.values()) # Output: dict_values(['Alice', 'New York'])

3. Dictionary Methods

  • d.keys(): Returns all the keys.
  • d.values(): Returns all the values.
  • d.items(): Returns all the key-value pairs as tuples.
  • d.get(key): Returns the value for the given key (returns None if key is not found).
  • d.pop(key): Removes the item with the specified key and returns the corresponding value.
  • d.update(other_dict): Merges another dictionary into the current dictionary.

Example:

# Example of dictionary methods d = {'name': 'Bob', 'age': 30} # Get method print(d.get('name')) # Output: Bob # Update method d.update({'age': 31, 'city': 'Paris'}) print(d) # Output: {'name': 'Bob', 'age': 31, 'city': 'Paris'} # Pop method age = d.pop('age') print(age) # Output: 31 print(d) # Output: {'name': 'Bob', 'city': 'Paris'}

4. Sparse Matrices

A sparse matrix is a matrix where most of the elements are zero (or some default value). In Python, sparse matrices can be represented using dictionaries, where keys are the positions of the non-zero elements.

Example:

# Sparse matrix representation using a dictionary sparse_matrix = { (0, 1): 5, (1, 2): 3, (2, 3): 7 } # Accessing a non-zero element print(sparse_matrix.get((0, 1), 0)) # Output: 5 print(sparse_matrix.get((0, 0), 0)) # Output: 0 (default value)

5. Aliasing and Copying

  • Aliasing occurs when two variables refer to the same object. Changing one variable will affect the other.
  • Copying creates a new independent object. Python provides copy() for shallow copies and deepcopy() for deep copies.

Example:

import copy # Aliasing example d1 = {'name': 'Alice'} d2 = d1 # d2 is now an alias of d1 d2['name'] = 'Bob' print(d1['name']) # Output: Bob (d1 and d2 refer to the same object) # Shallow copy d3 = d1.copy() # Creates a shallow copy d3['name'] = 'Charlie' print(d1['name']) # Output: Bob (d1 is not affected) # Deep copy d4 = copy.deepcopy(d1) # Creates a deep copy (nested objects are also copied) d4['name'] = 'Dave' print(d1['name']) # Output: Bob (d1 is not affected)
Dictionary Built-in Functions

Dictionary Built-in Functions

Function Description Example
len() Returns the number of key-value pairs in the dictionary. len({'name': 'Alice', 'age': 25}) → 2
keys() Returns a view object that displays a list of all the dictionary's keys. {'name': 'Alice', 'age': 25}.keys() → dict_keys(['name', 'age'])
values() Returns a view object that displays a list of all the dictionary's values. {'name': 'Alice', 'age': 25}.values() → dict_values(['Alice', 25])
items() Returns a view object that displays a list of dictionary's key-value tuple pairs. {'name': 'Alice', 'age': 25}.items() → dict_items([('name', 'Alice'), ('age', 25)])
get() Returns the value for a given key, or `None` if the key does not exist. {'name': 'Alice'}.get('name') → 'Alice'

Post a Comment

If you have any doubt, Please let me know.

Previous Post Next Post