0% found this document useful (0 votes)
1 views54 pages

8 - Python - Data Structures

The document provides an overview of Python's built-in data structures, focusing on lists, tuples, and dictionaries. It details how to create, access, modify, and perform operations on these data structures, along with their unique characteristics and use cases. Lists are mutable and allow duplicates, tuples are immutable, and dictionaries store data in key-value pairs, making them versatile for various programming needs.

Uploaded by

Mikru Birhan
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)
1 views54 pages

8 - Python - Data Structures

The document provides an overview of Python's built-in data structures, focusing on lists, tuples, and dictionaries. It details how to create, access, modify, and perform operations on these data structures, along with their unique characteristics and use cases. Lists are mutable and allow duplicates, tuples are immutable, and dictionaries store data in key-value pairs, making them versatile for various programming needs.

Uploaded by

Mikru Birhan
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

Python: Data Structures

by : Emmersive Learning

Join us :
Telegram : [Link]
Youtube :
[Link]
Data Structures

● Python provides several built-in data structures that allow you to organise
and store data efficiently.
● These include lists, tuples, dictionaries, sets, and more. Let’s go through
each of these in detail.
Built in Non Primitive

1. Lists

Lists are ordered, mutable (changeable), and allow duplicate elements. They are
defined using square brackets [].
1. Creating Lists

A list in Python is created using square brackets [], and elements are separated
by commas.

Example:

Python code:

# Creating a list of strings


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

# Creating a list of integers


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

# Creating a list of mixed data types


mixed = [1, "apple", 3.5, True]

2. Accessing List Elements


List elements can be accessed by their index, which starts at 0 for the first
element and -1 for the last element.

Example:

Python code

# Accessing elements
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry

3. Modifying Lists

Lists are mutable, meaning their elements can be changed after the list is
created.

Example:

Python code

# Modifying elements
fruits[1] = "blueberry"
print(fruits) # Output: ['apple', 'blueberry', 'cherry']

4. Adding Elements

a. append()

Adds an element to the end of the list.


Python code፡

[Link]("orange")
print(fruits) # Output: ['apple', 'blueberry', 'cherry',
'orange']

b. insert()

Inserts an element at a specific position.

Python code

[Link](1, "kiwi")
print(fruits) # Output: ['apple', 'kiwi', 'blueberry',
'cherry', 'orange']

5. Removing Elements

a. remove()

Removes the first occurrence of a specified element.

Python code

[Link]("kiwi")
print(fruits) # Output: ['apple', 'blueberry', 'cherry',
'orange']
b. pop()

Removes and returns the element at a specified index (or the last element if no
index is specified).

Python code

popped_fruit = [Link]()
print(popped_fruit) # Output: orange
print(fruits) # Output: ['apple', 'blueberry', 'cherry']

c. del

Deletes an element at a specified index.

Python code

del fruits[1]
print(fruits) # Output: ['apple', 'cherry']

6. List Operations

a. Concatenation

Combines two lists using the + operator.

Python code

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
print(combined_list) # Output: [1, 2, 3, 4, 5, 6]

b. Repetition

Repeats the elements of a list using the * operator.

Python code

repeated_list = list1 * 3
print(repeated_list) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

c. Membership

Checks if an element is in the list using the in operator.

Python code

print(1 in list1) # Output: True


print(4 in list1) # Output: False

7. List Slicing

Extracts a subset of a list using the slicing syntax list[start:end].

Python code
subset = fruits[0:2]
print(subset) # Output: ['apple', 'cherry']

8. List Methods

a. sort()

Sorts the list in ascending order.

Python code

numbers = [3, 1, 4, 1, 5, 9]
[Link]()
print(numbers) # Output: [1, 1, 3, 4, 5, 9]
b. reverse()

Reverses the elements of the list.

Python code

[Link]()
print(numbers) # Output: [9, 5, 4, 3, 1, 1]

c. index()

Returns the index of the first occurrence of a specified element.

Python code

index = [Link]("cherry")
print(index) # Output: 1

d. count()

Returns the number of occurrences of a specified element.

Python code

count = [Link](1)
print(count) # Output: 2

e. copy()
Returns a shallow copy of the list.

Python code

fruits_copy = [Link]()
print(fruits_copy) # Output: ['apple', 'cherry']

f. clear()

Removes all elements from the list.

Python code

[Link]()
print(fruits) # Output: []

9. List Comprehensions

A concise way to create lists.

Python code

squares = [x**2 for x in range(10)]


print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

10. Nested Lists

Lists within lists.


Python code

nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


print(nested_list[0][1]) # Output: 2

Summary

● Creating lists: Using square brackets [].


● Accessing elements: Using indices.
● Modifying lists: Changing elements, adding, removing.
● List operations: Concatenation, repetition, membership.
● List slicing: Extracting sublists.
● List methods: sort(), reverse(), index(), count(), copy(),
clear().
● List comprehensions: Creating lists concisely.
● Nested lists: Lists within lists.

Lists are a fundamental data structure in Python, providing a versatile way to


store and manipulate collections of items.

2. Tuples

Tuples are an important data structure in Python that are similar to lists but have
some key differences. They are immutable, meaning once created, their
elements cannot be changed. Here's a comprehensive guide to understanding
tuples in Python.
1. Creating Tuples

Tuples are defined using parentheses () with elements separated by commas.

Example:

Python code:
# Creating a tuple of strings
fruits = ("apple", "banana", "cherry")

# Creating a tuple of integers


numbers = (1, 2, 3, 4, 5)

# Creating a tuple of mixed data types


mixed = (1, "apple", 3.5, True)

# Creating an empty tuple


empty_tuple = ()

For a single element tuple, a comma is needed to avoid confusion with


parentheses used for other purposes.

Python code:

single_element_tuple = (42,)

2. Accessing Tuple Elements

Like lists, tuple elements can be accessed by their index, which starts at 0.

Example:
Python code:
# Accessing elements

print(fruits[0]) # Output: apple


print(fruits[-1]) # Output: cherry

3. Tuple Immutability

Once a tuple is created, its elements cannot be modified, added, or removed.


Any attempt to do so will result in an error.

Example:
Python code:

# Attempting to change an element (will raise an error)


# fruits[1] = "blueberry" # TypeError: 'tuple' object does not
support item assignment

# Attempting to add an element (will raise an error)


# [Link]("orange") # AttributeError: 'tuple' object has
no attribute 'append'

4. Tuple Operations

a. Concatenation

Combines two or more tuples using the + operator.

Python code :
#Concatenating tuples

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined_tuple = tuple1 + tuple2
print(combined_tuple) # Output: (1, 2, 3, 4, 5, 6)

b. Repetition

Repeats the elements of a tuple using the * operator.

Python code :

repeated_tuple = tuple1 * 3
print(repeated_tuple) # Output: (1, 2, 3, 1, 2, 3, 1, 2, 3)

c. Membership

Checks if an element is in the tuple using the in operator.

Python code:

print(1 in tuple1) # Output: True


print(4 in tuple1) # Output: False

5. Tuple Slicing
Extracts a subset of a tuple using the slicing syntax tuple[start:end].

Python code:

subset = fruits[0:2]
print(subset) # Output: ('apple', 'banana')

6. Tuple Methods

Tuples support a limited number of methods compared to lists due to their


immutability.

a. count()

Returns the number of occurrences of a specified element.

Python code:

count = [Link](3)
print(count) # Output: 1

b. index()

Returns the index of the first occurrence of a specified element.

Python code:

index = [Link]("cherry")
print(index) # Output: 2

7. Nested Tuples

Tuples can contain other tuples, which is useful for complex data structures.

Python code :

nested_tuple = ((1, 2, 3), ("a", "b", "c"), (True, False, True))


print(nested_tuple[1][2]) # Output: c

8. Converting Between Lists and Tuples

You can convert a list to a tuple using the tuple() function and vice versa using
the list() function.

Example:
Python code :

# Converting a list to a tuple


fruits_list = ["apple", "banana", "cherry"]
fruits_tuple = tuple(fruits_list)
print(fruits_tuple) # Output: ('apple', 'banana', 'cherry')

# Converting a tuple to a list


numbers_list = list(numbers)
print(numbers_list) # Output: [1, 2, 3, 4, 5]
9. Packing and Unpacking Tuples

Packing

Assigning multiple values to a single variable as a tuple.

Python code:

packed_tuple = 1, 2, 3
print(packed_tuple) # Output: (1, 2, 3)

Unpacking

Assigning the elements of a tuple to multiple variables.

Python code:

a, b, c = packed_tuple
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3

10. Tuple Use Cases

Due to their immutability, tuples are often used for:

● Fixed collections of data.


● Keys in dictionaries (when the keys are multi-part).
● Returning multiple values from a function.
Summary

● Creating tuples: Using parentheses () or without for single elements.


● Accessing elements: Using indices.
● Immutability: Cannot modify, add, or remove elements.
● Tuple operations: Concatenation, repetition, membership.
● Tuple slicing: Extracting sub-tuples.
● Tuple methods: count() and index().
● Nested tuples: Tuples within tuples.
● Conversion: Between lists and tuples.
● Packing and unpacking: Assigning multiple values to/from tuples.

Tuples are a powerful tool in Python, especially when you need a data structure
that should not change.

Difference between Tuple and List


3. Dictionaries

Dictionaries in Python are powerful and flexible data structures that allow you to
store and manage data using key-value pairs. They are particularly useful when
you need to associate values with unique keys.

1. What is a Dictionary?

A dictionary is a collection of key-value pairs. Each key is unique, and it maps to


a corresponding value. Unlike lists or tuples, dictionaries are unordered, meaning
the items are not stored in a specific sequence.
2. Creating a Dictionary

Dictionaries are created using curly braces {} with key-value pairs separated by
colons :.

Example:
Python code :

# Creating a dictionary with string keys


person = {
"name": "John",
"age": 30,
"city": "New York"
}

# Creating a dictionary with mixed data types


student = {
"name": "Alice",
"age": 22,
"grades": [90, 85, 88],
"graduate": False
}

# Creating an empty dictionary


empty_dict = {}

3. Accessing Dictionary Values

You can access dictionary values by referring to their keys.

Example:
Python code:

# Accessing values using keys


print(person["name"]) # Output: John
print(student["grades"]) # Output: [90, 85, 88]

4. Modifying a Dictionary
Dictionaries are mutable, so you can change, add, or remove key-value pairs.

a. Changing Values

You can update the value associated with a specific key.

Python code:

person["age"] = 31
print(person["age"]) # Output: 31

b. Adding Key-Value Pairs

You can add new key-value pairs to a dictionary.

Python code:

person["occupation"] = "Engineer"
print(person) # Output: {'name': 'John', 'age': 31, 'city':
'New York', 'occupation': 'Engineer'}

c. Removing Key-Value Pairs

You can remove key-value pairs using the del keyword or the pop() method.

Python code:

# Using del
del person["city"]
print(person) # Output: {'name': 'John', 'age': 31,
'occupation': 'Engineer'}

# Using pop()
age = [Link]("age")
print(age) # Output: 31
print(person) # Output: {'name': 'John', 'occupation':
'Engineer'}

5. Dictionary Methods

a. keys()

Returns a view object containing all the keys in the dictionary.


Python code:

print([Link]()) # Output: dict_keys(['name',


'occupation'])

b. values()

Returns a view object containing all the values in the dictionary.

Python code:

int([Link]()) # Output: dict_values(['John',


'Engineer'])

c. items()

Returns a view object containing all the key-value pairs in the dictionary.

Python code

print([Link]()) # Output: dict_items([('name', 'John'),


('occupation', 'Engineer')])

d. update()
Updates the dictionary with the key-value pairs from another dictionary or from
an iterable of key-value pairs.

Python code:

[Link]({"age": 32, "city": "Boston"})


print(person) # Output: {'name': 'John', 'occupation':
'Engineer', 'age': 32, 'city': 'Boston'}

e. get()

Returns the value associated with a key. If the key does not exist, it returns None
(or a specified default value).

Python code:

print([Link]("name")) # Output: John


print([Link]("salary", "Not available")) # Output: Not
available

f. clear()

Removes all key-value pairs from the dictionary.

Python code:

[Link]()
print(person) # Output: {}
6. Looping Through a Dictionary

You can loop through a dictionary to access keys, values, or key-value pairs.

Example:
Python code:

# Looping through keys


for key in student:
print(key)

# Looping through values


for value in [Link]():
print(value)

# Looping through key-value pairs


for key, value in [Link]():
print(f"{key}: {value}")

7. Dictionary Comprehensions

Similar to list comprehensions, you can create dictionaries using dictionary


comprehensions.

Example:
Python code:
squares = {x: x*x for x in range(6)}
print(squares) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

8. Nesting Dictionaries

Dictionaries can contain other dictionaries, allowing you to create complex data
structures.

Example:
Python code:

nested_dict = {
"John": {"age": 30, "city": "New York"},
"Alice": {"age": 25, "city": "London"},
"Bob": {"age": 35, "city": "San Francisco"}
}

print(nested_dict["Alice"]["city"]) # Output: London

9. Dictionary Use Cases

Dictionaries are often used when you need to:

● Associate unique keys with values (e.g., mapping names to phone


numbers).
● Store and retrieve data quickly (e.g., using keys as indexes).
● Store configuration settings or parameters.
Summary

● Creating dictionaries: Using curly braces {} with key-value pairs.


● Accessing values: Using keys.
● Modifying dictionaries: Changing, adding, or removing key-value pairs.
● Dictionary methods: keys(), values(), items(), update(), get(),
clear().
● Looping through dictionaries: Iterating over keys, values, or key-value
pairs.
● Dictionary comprehensions: Creating dictionaries in a concise way.
● Nesting dictionaries: Storing dictionaries within dictionaries for complex
data structures.

Dictionaries are a fundamental data structure in Python, and they offer great
flexibility and performance for many programming tasks.

4. Sets

Sets in Python are a built-in data structure that allows you to store unique
elements in an unordered collection. They are useful when you need to perform
operations like union, intersection, difference, and membership testing with
collections of data.
1. What is a Set?

A set is an unordered collection of unique elements. Unlike lists or tuples, sets do


not allow duplicate elements, and they do not maintain any order. Sets are
defined using curly braces {} or the set() function.

2. Creating a Set

You can create a set by placing all the elements within curly braces {} or by
using the set() function.

Example:
Python code:

# Creating a set of integers


numbers = {1, 2, 3, 4, 5}
# Creating a set of mixed data types
mixed_set = {1, "apple", 3.5, True}

# Creating an empty set


empty_set = set() # Note: {} creates an empty dictionary, not a
set.

3. Set Characteristics

● Unordered: The elements in a set do not have a specific order.


● Unique: Duplicate elements are automatically removed.

Example:
Python code:

# Demonstrating uniqueness
duplicates_set = {1, 2, 2, 3, 4, 4, 5}
print(duplicates_set) # Output: {1, 2, 3, 4, 5}

4. Accessing Set Elements

Since sets are unordered, you cannot access elements by index. However, you
can loop through the elements using a for loop.

Example:
Python code :

for item in numbers:


print(item)

5. Modifying a Set

Sets are mutable, meaning you can add, remove, or modify elements.

a. Adding Elements

You can add a single element using the add() method or multiple elements
using the update() method.

Python code:
[Link](6)
print(numbers) # Output: {1, 2, 3, 4, 5, 6}

[Link]([7, 8, 9])
print(numbers) # Output: {1, 2, 3, 4, 5, 6, 7, 8, 9}

b. Removing Elements

You can remove elements using the remove() or discard() method. The
pop() method removes and returns an arbitrary element.

Python code :

[Link](9) # Removes 9 from the set


print(numbers) # Output: {1, 2, 3, 4, 5, 6, 7, 8}

[Link](8) # Removes 8 from the set


print(numbers) # Output: {1, 2, 3, 4, 5, 6, 7}

# Using pop()
removed_item = [Link]()
print(removed_item) # Output: (arbitrary item, e.g., 1)
print(numbers) # Output: Set without the popped item

6. Set Operations
Sets support several standard operations for mathematical set theory, such as
union, intersection, difference, and symmetric difference.

a. Union

Combines two sets, returning a new set containing all unique elements from both
sets.

Python code:

set1 = {1, 2, 3}
set2 = {3, 4, 5}
union_set = [Link](set2)
print(union_set) # Output: {1, 2, 3, 4, 5}

# Alternatively, you can use the '|' operator


union_set = set1 | set2
print(union_set) # Output: {1, 2, 3, 4, 5}

b. Intersection

Returns a new set containing only the elements common to both sets.

Python code:

intersection_set = [Link](set2)
print(intersection_set) # Output: {3}

# Alternatively, you can use the '&' operator


intersection_set = set1 & set2
print(intersection_set) # Output: {3}

c. Difference

Returns a new set containing elements in the first set but not in the second set.

Python code:

difference_set = [Link](set2)
print(difference_set) # Output: {1, 2}
# Alternatively, you can use the '-' operator
difference_set = set1 - set2
print(difference_set) # Output: {1, 2}

d. Symmetric Difference

Returns a new set containing elements that are in either of the sets but not in
both.

Python code:

symmetric_difference_set = set1.symmetric_difference(set2)
print(symmetric_difference_set) # Output: {1, 2, 4, 5}

# Alternatively, you can use the '^' operator


symmetric_difference_set = set1 ^ set2
print(symmetric_difference_set) # Output: {1, 2, 4, 5}

7. Set Methods
a. issubset()

Checks if all elements of the first set are in the second set.

Python code:

print([Link](set2)) # Output: False


print({1, 2}.issubset(set1)) # Output: True

b. issuperset()
Checks if the first set contains all elements of the second set.

Python code:

print([Link](set2)) # Output: False


print([Link]({1, 2})) # Output: True

c. isdisjoint()

Checks if two sets have no elements in common.

Python code:

print([Link](set2)) # Output: False


print([Link]({6, 7})) # Output: True

8. Frozen Sets

A frozenset is an immutable version of a set. Once created, you cannot modify its
elements, but you can still perform set operations like union, intersection, etc.

Example:
Python code :

frozen_set = frozenset([1, 2, 3, 4])


print(frozen_set) # Output: frozenset({1, 2, 3, 4})

# Attempting to add or remove elements will raise an error


# frozen_set.add(5) # AttributeError: 'frozenset' object has no
attribute 'add'

9. Use Cases for Sets

● Removing Duplicates: Sets automatically remove duplicates, so they are


great for getting unique items from a list.
● Membership Testing: Checking if an item is in a set is faster than in lists.
● Mathematical Operations: Sets are ideal for operations like union,
intersection, and difference.

Summary

● Creating sets: Using {} or set() with unique elements.


● Accessing elements: Sets are unordered, so no indexing, but you can
loop through.
● Modifying sets: Add or remove elements using add(), remove(),
discard(), or pop().
● Set operations: Union, intersection, difference, and symmetric difference.
● Set methods: issubset(), issuperset(), isdisjoint().
● Frozen sets: Immutable sets for situations where you need a fixed
collection of unique elements.

Sets are a versatile and powerful tool in Python, especially when working with
unique data and performing mathematical set operations. If you have any specific
questions or need further examples, feel free to ask!

5. Strings
Although not typically classified as a data structure, strings in Python are
sequences of characters and support various operations.

Strings in Python are sequences of characters enclosed within quotes. They are
one of the most commonly used data types, providing powerful tools for text
manipulation and processing.

1. What is a String?

A string is a sequence of characters (letters, digits, symbols, spaces, etc.)


enclosed in either single quotes ('), double quotes ("), or triple quotes (''' or
"""). Strings in Python are immutable, meaning once created, they cannot be
changed.

Example:

Python code:

# Single quotes
string1 = 'Hello, World!'
# Double quotes
string2 = "Python is fun!"

# Triple quotes (used for multi-line strings or docstrings)


string3 = '''This is a
multi-line string'''

print(string1)
print(string2)
print(string3)

2. Accessing Characters in a String

You can access individual characters in a string using indexing, where the index
starts from 0 for the first character. Negative indexing can be used to access
characters from the end of the string.

Example:

Python code:

string = "Python"

# Accessing characters by positive index


print(string[0]) # Output: P
print(string[1]) # Output: y

# Accessing characters by negative index


print(string[-1]) # Output: n
print(string[-2]) # Output: o

3. Slicing Strings

Slicing allows you to extract a part of the string by specifying a start and end
index. The syntax is string[start:end], where start is inclusive, and end
is exclusive.

Example:

Python code:

string = "Hello, World!"

# Slicing from index 0 to 4 (exclusive)


print(string[0:5]) # Output: Hello

# Slicing from index 7 to the end


print(string[7:]) # Output: World!

# Slicing the entire string


print(string[:]) # Output: Hello, World!

# Slicing with negative indices


print(string[-6:-1]) # Output: World

4. String Concatenation and Repetition


You can concatenate strings using the + operator and repeat strings using the *
operator.

Example:

Python code:

# Concatenation
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message) # Output: Hello, Alice!

# Repetition
laugh = "Ha" * 3
print(laugh) # Output: HaHaHa

5. String Methods
Python provides a wide range of built-in string methods for various operations
like formatting, searching, replacing, and more.

a. lower() and upper()

Converts the string to lowercase or uppercase.

Python code:

text = "Python Programming"


print([Link]()) # Output: python programming
print([Link]()) # Output: PYTHON PROGRAMMING

b. strip(), lstrip(), and rstrip()


Removes leading and trailing whitespace (or specified characters).

Python code:

text = " Hello, World! "


print([Link]()) # Output: Hello, World!
print([Link]()) # Output: "Hello, World! "
print([Link]()) # Output: " Hello, World!"

c. replace()

Replaces occurrences of a substring with another substring.

Python code:

text = "Hello, World!"


new_text = [Link]("World", "Python")
print(new_text) # Output: Hello, Python!

d. find()

Returns the index of the first occurrence of a substring. Returns -1 if the


substring is not found.

Python code:

text = "Hello, World!"


index = [Link]("World")
print(index) # Output: 7

e. split() and join()

● split(): Splits the string into a list of substrings based on a delimiter.


● join(): Joins a list of strings into a single string with a specified delimiter.

Python code :

text = "Python is fun"


words = [Link]() # Splitting by space
print(words) # Output: ['Python', 'is', 'fun']

joined_text = " ".join(words)


print(joined_text) # Output: Python is fun

f. startswith() and endswith()

Checks if the string starts or ends with a specified substring.

Python code:

text = "Hello, World!"


print([Link]("Hello")) # Output: True
print([Link]("World!")) # Output: True
6. String Formatting

Python provides several ways to format strings, allowing you to inject variables
into a string.

a. Using the format() Method

Python code:

name = "Alice"
age = 25
message = "My name is {} and I am {} years old.".format(name,
age)
print(message) # Output: My name is Alice and I am 25 years
old.

b. Using f-Strings (Python 3.6+)

Python code

name = "Bob"
age = 30
message = f"My name is {name} and I am {age} years old."
print(message) # Output: My name is Bob and I am 30 years old.

c. Using Percent (%) Formatting

Python code
name = "Charlie"
age = 28
message = "My name is %s and I am %d years old." % (name, age)
print(message) # Output: My name is Charlie and I am 28 years
old.

7. Escape Characters

Escape characters are used to insert special characters in strings. They are
preceded by a backslash (\).

Common Escape Characters:

● \': Single quote


● \": Double quote
● \\: Backslash
● \n: Newline
● \t: Tab

Example:

Python code:

text = "He said, \"Python is awesome!\""


print(text) # Output: He said, "Python is awesome!"

# Newline and tab


multi_line_text = "First Line\nSecond Line\tIndented"
print(multi_line_text)
# Output:
# First Line
# Second Line Indented

8. String Immutability

Strings in Python are immutable, meaning that once a string is created, it cannot
be modified. Any operation that modifies a string will create a new string.

Example:

Python code

text = "Hello"
text = text + " World"
print(text) # Output: Hello World

# The original "Hello" string remains unchanged; a new string


"Hello World" is created.

9. Multi-line Strings

You can create multi-line strings using triple quotes (''' or """). They are often
used for documentation strings (docstrings) or when you need to include line
breaks in the string.

Example:
Python code:

multi_line_string = """This is a multi-line string.


It can span multiple lines.
You can include line breaks."""

print(multi_line_string)

Summary

● Creating strings: Using single, double, or triple quotes.


● Accessing characters: Via indexing or slicing.
● String methods: lower(), upper(), strip(), replace(), find(),
split(), join(), startswith(), endswith().
● String formatting: Using format(), f-strings, or % formatting.
● Escape characters: Inserting special characters like newlines and tabs.
● Immutability: Strings cannot be changed in place; operations create new
strings.
● Multi-line strings: Using triple quotes for strings that span multiple lines.

Strings are a fundamental part of Python programming, essential for tasks


ranging from simple text processing to complex data manipulation. If you have
more questions or need further examples, feel free to ask!

6. User Defined Data Structures


a. Arrays

In Python, arrays are not a built-in data type like lists or dictionaries, but you can
use lists to achieve similar functionality or use external libraries like array or
numpy for more advanced operations.

For numerical operations, you can use arrays from the array module or libraries
like NumPy.

Python code

import array as arr


numbers = [Link]('i', [1, 2, 3, 4, 5])
b. Deques

For efficient appends and pops from both ends of a list, use
[Link].

Python code

from collections import deque


d = deque([1, 2, 3])
[Link](4)
[Link](0)
print(d) # Output: deque([0, 1, 2, 3, 4])

Learn Data Structure in Python for more on user defined DS.

7. Summary

● Lists: Ordered, mutable, allow duplicates.


● Tuples: Ordered, immutable, allow duplicates.
● Dictionaries: Unordered, mutable, indexed by keys.
● Sets: Unordered, mutable, no duplicates.
● Strings: Immutable sequences of characters.
● Arrays: Efficient numerical operations.
● Deques: Efficient double-ended queue operations.

Understanding these data structures and how to use them effectively is crucial for
efficient and effective Python programming.
Thank You and Happy Coding!

Mehammed Teshome From Emmersive Learning

You might also like