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:
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:
Example:
String Traversal
- String traversal means iterating through the characters of a string, one by one, using loops (e.g.,
for
loop).
Example:
Output:
- 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:
- 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:
Here:
my_string[0:5]
returns characters from index0
to4
(i.e., "Hello").my_string[7:]
returns everything from index7
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:
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:
Example:
Looping Through a String
- You can loop over a string in various ways, including using
for
loops orwhile
loops. Thefor
loop iterates through each character of the string.
Example (using for
loop):
Example (using while
loop):
Counting Substrings in a String
- The
count()
method counts how many times a substring appears in the string.
Syntax:
Example:
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!" |
capitalize() |
Capitalizes the first character of the string and makes all other characters lowercase. | my_string = "hello, python!" |
casefold() |
Returns a case-insensitive version of the string (useful for case-insensitive comparisons). | my_string = "HELLO, PYTHON!" |
lower() |
Converts all characters in the string to lowercase. | my_string = "HELLO, PYTHON!" |
upper() |
Converts all characters in the string to uppercase. | my_string = "hello, python!" |
swapcase() |
Swaps the case of all characters in the string (upper to lower and vice versa). | my_string = "Hello, Python!" |
strip() |
Removes leading and trailing whitespace characters from the string. | my_string = " Hello, Python! " |
lstrip() |
Removes leading (left) whitespace characters from the string. | my_string = " Hello, Python!" |
rstrip() |
Removes trailing (right) whitespace characters from the string. | my_string = "Hello, Python! " |
replace() |
Replaces occurrences of a substring with another substring. | my_string = "Hello, Python!" |
split() |
Splits the string into a list of substrings based on a delimiter (default is whitespace). | my_string = "Hello, Python!" |
join() |
Joins elements of a list into a string, using a specified delimiter. | my_list = ['Hello', 'Python', 'World'] |
find() |
Returns the index of the first occurrence of a substring. Returns -1 if not found. | my_string = "Hello, Python!" |
startswith() |
Returns True if the string starts with the specified substring. | my_string = "Hello, Python!" |
endswith() |
Returns True if the string ends with the specified substring. | my_string = "Hello, Python!" |
isdigit() |
Returns True if all characters in the string are digits. | my_string = "12345" |
isalpha() |
Returns True if all characters in the string are alphabetic. | my_string = "Hello" |
format() |
Inserts variables or values into placeholders in a string. | name = "Python" |
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
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
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
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.
2. Length of a List:
The len()
function is used to get the number of elements in a list.
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.
4. List Operations:
- Concatenation: You can concatenate two or more lists using the
+
operator.
- Repetition: You can repeat a list using the
*
operator.
5. List Slicing:
List slicing allows you to extract a portion of the list. The syntax for slicing is list[start:end:step]
.
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.
- Using
remove()
: Removes the first occurrence of a specified value.
- Using
pop()
: Removes an element by index and returns it.
You can access list elements using their index. Remember that Python uses zero-based indexing.
8. List and for
Loops:
You can loop through a list using a for
loop to access each element.
9. List Parameters:
Lists can be passed as arguments to functions. You can also return a list from a function.
10. Nested Lists:
Lists can contain other lists as elements, allowing you to create multidimensional data structures (like matrices).
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] |
extend() |
Appends all elements of an iterable (e.g., list) to the end of the list. | my_list = [1, 2, 3] |
insert() |
Inserts an element at a specified index. | my_list = [1, 2, 3] |
remove() |
Removes the first occurrence of a specified value. | my_list = [1, 2, 3, 4] |
pop() |
Removes and returns the element at a specified index (default is the last element). | my_list = [1, 2, 3] |
sort() |
Sorts the list in ascending order. Can take `reverse=True` for descending order. | my_list = [3, 1, 2] |
reverse() |
Reverses the elements of the list in place. | my_list = [1, 2, 3] |
count() |
Returns the number of occurrences of a specified value in the list. | my_list = [1, 2, 2, 3, 2] |
index() |
Returns the index of the first occurrence of a specified value. | my_list = [1, 2, 3] |
clear() |
Removes all elements from the list. | my_list = [1, 2, 3] |
list() |
Creates a new list from an iterable (e.g., a string, tuple, or set). | my_string = "hello" |
Creating an Empty List |
Creates an empty list. | empty_list = [] |
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:
2. Tuple Assignment
Tuple assignment is a technique where you can assign values to multiple variables at once using a tuple.
Example:
3. Tuples as Return Values
Functions can return tuples, making it easy to return multiple values.
Example:
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:
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:
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:
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 (returnsNone
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:
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:
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 anddeepcopy()
for deep copies.
Example:
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' |