0% found this document useful (0 votes)
2 views39 pages

UNIT 2 Python

Uploaded by

primusdsouza74
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)
2 views39 pages

UNIT 2 Python

Uploaded by

primusdsouza74
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

UNIT 2

Strings: Creating and Storing Strings; Accessing Sting Characters; the str() function; Operations
on Strings- Concatenation, Comparison, Slicing and Joining, Traversing; Python String Methods.
Strings:
 A string consists of a sequence of characters, which includes letters, numbers, punctuation marks
and spaces.
 To represent strings, you can use a single quote, double quotes or triple quotes.
 Strings are another basic data type available in Python.

Creating and Storing Strings:


 We can create and store strings by assigning them to variables using the assignment operator (=).
1. Using single quotes
greeting = 'Hello, World'

2. Using double quotes


book_title = "Python Programming"

3. Single character string. A single character like "A" is also a string.


grade = "A"

4. Empty strings. An empty string contains no characters and can be written as '' or "".
empty1 = ''
empty2 = ""

5. String with single quote inside double quotes


line1 = "Don't worry, be happy"

6. String with double quotes inside single quotes


line2 = 'It is a "Python" class.'

7. Escaping same quote type using backslash


line3 = 'It\'s a nice day'

8. Multi-line string using triple quotes


line4 = '''This is a multi-line string'''
line5 = """This is a multi-line string"""

 The type of a string variable can be checked using type() function.


type(greeting)

Output:
<class 'str'>

The str() function:

 The str() function in Python is used to convert an object into its string representation. If the object is
not provided, then it returns an empty string.
 Syntax:
str(object)

 Examples:
1. Convert number to string:
num = 123
s = str(num)
print(s) # Output: '123'
print(type(s)) # Output: <class 'str'>
2. Convert list to string:
lst = [1, 2, 3]
s = str(lst)
print(s) # Output: '[1, 2, 3]'
3. Convert boolean to string:
b = True
print(str(b)) # Output: 'True'
4. Create an empty string:
String = str()
type(String) # Output: <class ‘str’>

Basic String operations:

 Concatenation (+): Joins two strings. Python cannot concatenate string value with integer value
since they are of different data types. You need to convert integer type to string type before
concatenating integer and string values.
 Example:
s1 = "Hello"
s2 = "World"
print(s1 + " " + s2) # Output: Hello World

singer = str(50) + "cent"


print(singer) # Output: '50cent'

 Repetition (*): Repeats a string multiple time.


 Example:
print("Hi! " * 3) # Output: Hi! Hi! Hi!

 Membership operators in Python:


Membership operators in Python are used to test whether a value is a member of a sequence, such
as a string, list, tuple, or set. Python provides two membership operators: in and not in. These
operators return a Boolean value, True or False, based on whether the specified value is found in the
sequence.

1. in Operator:
The in operator is used to check if a value is present in a sequence.

Syntax:

value in sequence
Example:
colors = ['red', 'green', 'blue']
is_green = 'green' in colors # True
is_yellow = 'yellow' in colors # False

2. not in Operator:
The not in operator is used to check if a value is not present in a sequence.
Syntax:
value not in sequence

Example:

numbers = [1, 2, 3, 4, 5]
is_6_missing = 6 not in numbers # True
is_2_missing = 2 not in numbers # False

Membership operators are frequently used in various scenarios:


1. Searching in Lists:
You can use in to quickly check if an element exists in a list.

if 'apple' in fruit_list:
print("Found apple in the list.")

2. Checking for Substrings:


in is useful for checking if a substring exists in a string.

if 'world' in greeting:
print("Found 'world' in the greeting.")

3. Testing Set Membership:


You can use in and not in to test whether an element is present in a set.

if 42 in my_set:
print("The number 42 is in the set.")

4. Conditional Statements:
Membership operators can be used in conditional statements to control the flow of your program.

if user_input in valid_options:
# Process user input
else:
print("Invalid input.")

5. Iterating Through Sequences:


You can use in to iterate through elements in a sequence.
for item in my_list:
print(item)

String Comparison
 Strings can be compared using relational operators:
 ==, !=, >, <, >=, <=
 The comparison is done character by character, based on ASCII values.

Examples:
"january" == "jane" # False
"january" != "jane" # True
"january" < "jane" # False
"january" > "jane" # True
"january" <= "jane" # False
"january" >= "jane" # True
"filled" > "" # True

Built-in functions used on Strings:


The len() function in Python is used to determine the length of a string, which is the number of
characters in the string. It can be used with any string, including single characters, words, or entire
paragraphs.

len(string)

Where string is the string for which you want to find the length.

Example:
text = "Hello, World!"
length = len(text)
print("The length of the string is:", length)

Output:
The length of the string is: 13

The max() and min() function:


In Python, the max() and min() functions can be used with strings to find the maximum and minimum
characters based on their Unicode code points (ordinal values) within the string.

- max(string): Returns the character with the highest ASCII/Unicode code point in the string.
- min(string): Returns the character with the lowest ASCII/Unicode code point in the string.

text = "Hello, World!"


max_char = max(text)
min_char = min(text)

print("Maximum character:", max_char)


print("Minimum character:", min_char)

Output:
Maximum character: r
Minimum character:
Accessing characters in strings and string slicing:
To access an individual character in a string, you can use indexing. Python uses 0-based indexing,
meaning the first character is at index 0, the second character is at index 1, and so on. You can also use
negative indexing to count characters from the end of the string, with -1 representing the last character.

Syntax:
character = string[index]

Example:
text = "Python"
first_char = text[0] # Access the first character ('P')
second_char = text[1] # Access the second character ('y')
last_char = text[-1] # Access the last character ('n')

print(first_char)
print(second_char)
print(last_char)

Output:
P
y
n

What is use of negative indexing in string? Give example.


 We can also access individual characters in a string using negative indexing.
 The negative index can be used to access individual characters in a string.
 Negative indexing starts with −1 index corresponding to the last character in the string and then the
index decreases by one as we move to the left.
 If you have a long string and want to access end characters in the string, then you can count
backward from the end of the string starting from an index number of −1.
 The negative index break down for the string “be yourself” assigned to word_phrase string variable
is

>>> word_phrase[-1]
'f'
>>> word_phrase[-2]
'l'

>>> healthy_drink[-3:-1]
'te'
>>> healthy_drink[6:-1]
'te'
 You need to specify the lowest negative integer number in the start index position when using
negative index numbers as it occurs earlier in the string.
 You can also combine positive and negative indexing numbers.
 You can benefit from using negative indexing when you want to access characters at the end of a
long string.

Slicing a String:

String slicing allows you to extract a portion of a string, creating a new substring. It uses the [start:stop]
notation, where start is the index where the slice begins (inclusive) and stop is the index where the slice
ends (exclusive).

Syntax for Slicing:


substring = string[start:stop]
- string: The string you want to slice.
- start: The starting index of the slice (inclusive).
- stop: The ending index of the slice (exclusive).

Example:
text = "Python Programming"
substring1 = text[0:6] # Slice the first 6 characters ('Python')
substring2 = text[7:18] # Slice the word 'Programming'
substring3 = text[7:] # Slice from the 7th character to the end
substring4 = text[:6] # Slice from the beginning up to the 6th character

print(substring1)
print(substring2)
print(substring3)
print(substring4)

Output:
Python
Programming
Programming
Python

Slicing with Step Value:

You can specify a step value to skip characters when slicing. The syntax for this is:
substring = string[start:stop:step]

Example with Step Value:


text = "Python Programming"
substring = text[0:18:2] # Slice every 2nd character ('Pto rgamn')
print(substring)

Output:
Pto rgamn

Give the syntax and example for split function.


 The split() method returns a list of string items by breaking up the string using the delimiter
string.
 The syntax of split() method is,
string_name.split([separator [, maxsplit]])
 Here separator is the delimiter string and is optional.
 A given string is split into list of strings based on the specified separator.
 If the separator is not specified then whitespace is considered as the delimiter string to separate
the strings.
 If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit +
1 items).
 If maxsplit is not specified or −1, then there is no limit on the number of splits.
 Examples:
>>> inventors = "edison, tesla, marconi, newton"
>>> [Link](",")
['edison', ' tesla', ' marconi', ' newton']

>>> watches = "rolex hublot cartier omega"


>>> [Link]()
['rolex', 'hublot', 'cartier', 'omega']
 The value in inventors string variable is separated based on "," (comma) separator.
 The value in watches no separator is specified in split() method.
 Hence, the string variable watches is separated based on whitespace.

Explain join() method of string with example.


 Strings can be joined with the join() string.
 The join() method provides a flexible way to concatenate strings.
 The syntax of join() method is,
string_name.join(sequence)
 Here sequence can be string or list.
 If the sequence is a string, then join() function inserts string_name between each character of the
string sequence and returns the concatenated string.
 If the sequence is a list, then join() function inserts string_name between each item of list
sequence and returns the concatenated string.
 It should be noted that all the items in the list should be of string type.
 Examples:
>>> words = ["This", "is", "a", "list"]
>>> joined_string = " ".join(words)
>>> joined_string
'This is a list'
>>> new_string = ":".join(words)
>>> new_string
'This:is:a:list'
>>> numbers = "123"
>>> characters = "amy"
>>> password = [Link](characters)
>>> password
'a123m123y'
Strings are immutable:
In Python, strings are immutable, which means that once a string is created, it cannot be changed. When
you perform operations on a string, such as slicing, concatenation, or replacement, a new string is
created as the result. The original string remains unchanged.
>>> immu="dollar"
>>> immu[0]='c'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
immu[0]='c'
TypeError: 'str' object does not support item assignment

Traversing a string involves iterating through the characters of the string one by one. You can traverse
a string using a for loop or a while loop, examining each character as you go through the string.
Syntax for Traversing a String:

Using a for loop:


for char in string:
# Process each character (char)

Using a while loop:


index = 0
while index < len(string):
char = string[index]
# Process the character (char)
index += 1

Example of Traversing a String:


text = "Python"

# Using a for loop to traverse the string


print("Using a for loop:")
for char in text:
print(char, end=' ')
print()

# Using a while loop to traverse the string


print("Using a while loop:")
index = 0
while index < len(text):
print(text[index], end=' ')
index += 1

Output:
Using a for loop:
Python
Using a while loop:
Python

String methods
1. [Link]() and [Link]()
- [Link](): Converts all characters in a string to uppercase.
- [Link](): Converts all characters in a string to lowercase.

original_string = "Hello, World!"


upper_case = original_string.upper() # "HELLO, WORLD!"
lower_case = original_string.lower() # "hello, world!"

2. [Link]([chars])
- The method strip() returns a copy of the str in which specified chars have been stripped from both
side of the string. If chars is not specified then space is taken as default.
text = " This is a text with extra whitespace. "
stripped_text = [Link]() # "This is a text with extra whitespace."

3. [Link]()
- [Link](substring): Searches for a substring within the string and returns the index of its first
occurrence, or -1 if not found.
text = "This is a sample text. Is this a sample?"
first_occurrence = [Link]("sample") # 10
last_occurrence = [Link]("sample") # 26

4. [Link]()
- Replaces all occurrences of a substring with another string.
text = "Hello, World!"
new_text = [Link]("World", "Python") # "Hello, Python!"

5. [Link]() and [Link]()


- [Link](prefix): Checks if the string starts with the specified prefix and returns True or False.
- [Link](suffix): Checks if the string ends with the specified suffix and returns True or False.
text = "This is a test"
starts_with = [Link]("This") # True
ends_with = [Link]("test") # True

6. [Link]()
- Counts the number of non-overlapping occurrences of a substring within the string.
text = "How many times does 'is' appear in this sentence? This is it."
count = [Link]("is") # 4

7. [Link]()
- The capitalize() method returns a copy of the string with its first character capitalized and the rest
lowercased.
text = "hello, world"
capitalized_text = [Link]()
print("Original string:", text)
print("Capitalized string:", capitalized_text)

8. [Link]()
- The casefold() method returns a casefolded copy of the string. Casefolded strings may be used for
caseless matching.
>>> string1 = "Hello"
>>> string2 = "heLLO"
>>> [Link]() == [Link]()
True
9. center(width, fillchar):
- Centers the string within a given width, adding a specified fill character around it.
text = "Python"
centered_text = [Link](10, '*')
print(centered_text)

Output:
**Python**

10. isalnum():
- Checks if the string consists of alphanumeric characters (letters and digits).
text = "Python3"
result = [Link]()
print("Is alphanumeric:", result)

Output:
Is alphanumeric: True

11. isalpha():
- Checks if the string consists of alphabetic characters (letters).
text = "Python"
result = [Link]()
print("Is alphabetic:", result)

Output:
Is alphabetic: True
12. isdecimal():
- Checks if the string consists of decimal characters (digits).
text = "12345"
result = [Link]()
print("Is decimal:", result)

Output:
Is decimal: True

13. isdigit():
- Checks if the string consists of digits.
text = "12345"
result = [Link]()
print("Is digit:", result)

Output:
Is digit: True
14. isidentifier():
- Checks if the string is a valid Python identifier.
text = "class_name"
result = [Link]()
print("Is a valid identifier:", result)
Output:
Is a valid identifier: True
15. isspace():
- Checks if the string consists of only whitespace characters.
text = " \t "
result = [Link]()
print("Is whitespace:", result)
Output:
Is whitespace: True
16. isnumeric():
- Checks if the string consists of numeric characters.
text = "³"
result = [Link]()
print("Is numeric:", result)
Output:
Is numeric: True
17. istitle():
- Checks if the string follows title-casing (first letter of each word is capitalized).
text = "This Is a Title"
result = [Link]()
print("Is in title case:", result)

Output:
Is in title case: True

18. isupper():
- Checks if the string is in uppercase.
text = "ALL CAPS"
result = [Link]()
print("Is in uppercase:", result)

Output:
Is in uppercase: True

19. islower():
- Checks if the string is in lowercase.
text = "all lowercase"
result = [Link]()
print("Is in lowercase:", result)

Output:
Is in lowercase: True
20. ljust(width, fillchar):
- Left-aligns the string within a given width, adding a specified fill character on the right.
text = "Python"
left_aligned_text = [Link](10, '*')
print(left_aligned_text)

Output:
Python****

21. rjust(width, fillchar):


- Right-aligns the string within a given width, adding a specified fill character on the left.
text = "Python"
right_aligned_text = [Link](10, '*')
print(right_aligned_text)

Output:
****Python

22. title():
- Converts the string to title case.
text = "python programming"
title_text = [Link]()
print(title_text)

Output:
Python Programming

23. swapcase():
- Swaps the case of characters in the string (uppercase to lowercase and vice versa).
text = "PyThOn"
swapped_text = [Link]()
print(swapped_text)

Output:
pYtHoN

24. splitlines():
- Splits the string into a list of lines based on line breaks.

text = "Line 1\nLine 2\nLine 3"


lines = [Link]()
print("Split lines:", lines)

Output:
Split lines: ['Line 1', 'Line 2', 'Line 3']

25. rstrip():
- Removes trailing whitespace from the right side of the string.
text = " Right-Trim "
trimmed_text = [Link]()
print("Right-trimmed text:", trimmed_text)

Output:
Right-Trim

26. lstrip():
- Removes leading whitespace from the left side of the string.
text = " Left-Trim "
trimmed_text = [Link]()
print("Left-trimmed text:", trimmed_text)
Output:
Left-Trim

27. zfill(width):
- Pads the string with zeros on the left to achieve a specified width.
text = "42"
zero_padded_text = [Link](5)
print(zero_padded_text)

Output:
00042

Lists
Creating Lists:
A list in Python is a data structure that allows you to store a collection of items. Lists are ordered,
mutable (can be changed), and can contain elements of different data types. They are defined by
enclosing the elements in square brackets [ ] and separating them with commas.

Definition:
A list is a collection of elements that are ordered, mutable, and can contain elements of different data
types.

Syntax:
my_list = [element1, element2, element3, ...]

- my_list: The name of the list.


- element1, element2, element3, ...: The elements to be stored in the list.

Example:
>>> fruits = ["apple", "banana", "cherry"]
>>> fruits
['apple', 'banana', 'cherry']
 You can create an empty list without any items.
 The syntax is,
list_name = [ ]
 Example:
>>> empty_list=[]
>>> empty_list
[]

>>> number_list = [4, 4, 6, 7, 2, 9, 10, 15]


>>> mixed_list = ['dog', 87.23, 65, [9, 1, 8, 1]]
 You can store any item in a list like string, number, object, another variable and even another list.
 You can have a mix of different item types and these item types need not have to be homogeneous.
 For example, you can have a list which is a mix of type numbers, strings and another list itself.

You can access individual elements in a list using their index, which starts at 0. For example:

first_fruit = fruits[0]
print("First fruit:", first_fruit)

Output:
First fruit: apple

You can also modify, add, or remove elements from a list. Lists are versatile and widely used in Python
for various tasks like storing collections of data, performing operations on data, and more.

Basic List operations:


Concatenation (+) and Repetition (*) operators:
In Python, you can use the `+` and `*` operators on lists to perform concatenation and repetition,
respectively.

1. + Operator (Concatenation):
- The + operator is used to concatenate two or more lists, creating a new list that combines the
elements of the original lists.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2

- combined_list will be [1, 2, 3, 4, 5, 6], which is a new list that contains elements from both list1 and
list2. The original lists remain unchanged.

2. * Operator (Repetition):
- The * operator is used to create a new list by repeating the elements of an existing list a specified
number of times.

original_list = [1, 2]
repeated_list = original_list * 3

- repeated_list will be [1, 2, 1, 2, 1, 2], which is a new list created by repeating the elements of
original_list three times.

It's important to note that both the `+` and `*` operations on lists create new lists and do not modify the
original lists. The original lists remain unchanged after these operations.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
combined_list = list1 + list2
repeated_list = list1 * 3

print("Combined List:", combined_list)


print("Repeated List:", repeated_list)

Output:
Combined List: [1, 2, 3, 4, 5, 6]
Repeated List: [1, 2, 3, 1, 2, 3, 1, 2, 3]

The list() function:


The list() function in Python is used to create a new list. You can use it to convert other iterable data
structures, such as strings, tuples, or sets, into lists.

Syntax:
new_list = list(sequence)

- new_list: The new list that you want to create.


- sequence: A sequence object (e.g., a string, tuple, or set) that you want to convert into a list.

Examples and Output:


1. Converting a string into a list of characters:
text = "hello"
char_list = list(text)
print(char_list)

Output:
['h', 'e', 'l', 'l', 'o']

2. Converting a tuple into a list:


tuple_data = (1, 2, 3)
list_data = list(tuple_data)
print(list_data)

Output:
[1, 2, 3]
3. Converting a set into a list:
set_data = {4, 5, 6}
list_data = list(set_data)
print(list_data)

Output:
[4, 5, 6]
Write the output of the given python code :
aList = [123, 'xyz', 'zara', 'abc'];
[Link] (3,2009)
print ("Final List:", aList)

Output:
Final List: [123, 'xyz', 'zara', 2009, 'abc']

Indexing in list:
 As an ordered sequence of elements, each item in a list can be called individually, through indexing.
 The expression inside the bracket is called the index.
 Lists use square brackets [ ] to access individual items, with the first item at index 0, the second
item at index 1 and so on.
 The index provided within the square brackets indicates the value being accessed.
 The syntax for accessing an item in a list is,
list_name[index]
 where index should always be an integer value and indicates the item to be selected.
 For the list superstore, the index breakdown is shown below.

>>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]


>>> superstore[0]
'metro'
>>> superstore[3]
'kmart'
>>> superstore[9]
Traceback (most recent call last):
File "<pyshell#53>", line 1, in <module>
superstore[9]
IndexError: list index out of range

Negative indexing in list:


 In addition to positive index numbers, you can also access items from the list with a negative index
number, by counting backwards from the end of the list, starting at −1.
 Negative indexing is useful if you have a long list and you want to locate an item towards the end of
a list.
 For the list superstore, the negative index breakdown is shown below.

 Example:
>>> superstore[-3]
'walmart'

Slicing a list:
 Slicing of lists is allowed in Python wherein a part of the list can be extracted by specifying index
range along with the colon (:) operator which itself is a list.
 The syntax for list slicing is,
list_name[start:stop[:step]]
 where both start and stop are integer values (positive or negative values).
 List slicing returns a part of the list from the start index value to stop index value which includes the
start index value but excludes the stop index value.
 Step specifies the increment value to slice by and it is optional.
 For the list fruits, the positive and negative index breakdown is shown below.
>>> fruits = ["grapefruit", "pineapple", "blueberries", "mango", "banana"]
>>> fruits[1:3]
['pineapple', 'blueberries']
>>> fruits[:3]
['grapefruit', 'pineapple', 'blueberries']

>>> fruits[2:]
['blueberries', 'mango', 'banana']
>>> fruits[1:4:2]
['pineapple', 'mango']
>>> fruits[:]
['grapefruit', 'pineapple', 'blueberries', 'mango', 'banana']
>>> fruits[::2]
['grapefruit', 'blueberries', 'banana']
>>> fruits[::-1]
['banana', 'mango', 'blueberries', 'pineapple', 'grapefruit']
>>> fruits[-3:-1]
['blueberries', 'mango']

Modifying List Elements:


- You can change the value of an element in a list by assigning a new value to it.
- Syntax: list[index] = new_value

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


fruits[1] = "grape"
print("Updated fruits:", fruits)

Output:
Updated fruits: ['apple', 'grape', 'cherry']

Appending Items to a List:


- You can add an element to the end of a list using the append() method.
- Syntax: [Link](item)

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


[Link]("date")
print("Updated fruits:", fruits)

Output:
Updated fruits: ['apple', 'banana', 'cherry', 'date']
Built-in functions used on List:
1. len() Function:
- The len() function is used to determine the length (number of elements) in a list.

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


length = len(fruits)
print("Number of fruits:", length)

Output:
Number of fruits: 3

2. any() and all() Functions:


- any() returns True if at least one element in the list is True.
- all() returns True if all elements in the list are True.

bool_list = [True, False, True, True]


any_result = any(bool_list)
all_result = all(bool_list)
print("Any True:", any_result)
print("All True:", all_result)

Output:
Any True: True
All True: False

3. sum() Function:
- The sum() function is used to calculate the sum of all elements in a numeric list.

numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
print("Sum of numbers:", total)

Output:
Sum of numbers: 15

4. sorted() Function:
- The sorted() function is used to sort the elements of a list in ascending order and returns a new sorted
list.

numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
sorted_numbers = sorted(numbers)
print("Sorted numbers:", sorted_numbers)

Output:
Sorted numbers: [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

List Methods:
Python provides several built-in functions that can be used with lists to perform various operations.
These functions are designed to make common tasks with lists more convenient. Here's an explanation
of some commonly used built-in functions for lists with syntax and examples:
1. append()
- Syntax: [Link](item)
- Adds an item to the end of the list.
numbers = [1, 2, 3]
[Link](4)
# numbers now contains [1, 2, 3, 4]

2. extend()
- Syntax: [Link](iterable)
- Appends the elements of an iterable (e.g., another list) to the end of the list.
numbers = [1, 2, 3]
additional_numbers = [4, 5]
[Link](additional_numbers)
# numbers now contains [1, 2, 3, 4, 5]

3. insert()
- Syntax: [Link](index, item)
- Inserts an item at a specified position in the list.
colors = ["red", "green", "blue"]
[Link](1, "yellow")
# colors now contains ["red", "yellow", "green", "blue"]

4. remove()
- Syntax: [Link](item)
- Removes the first occurrence of an item from the list.
numbers = [1, 2, 3, 2, 4]
[Link](2)
# numbers now contains [1, 3, 2, 4]

5. pop()
- Syntax: [Link]([index])
- Removes and returns the item at the specified index. If no index is provided, it removes and returns
the last item in the list.
numbers = [1, 2, 3]
removed_item = [Link](1)
# removed_item is 2, numbers now contains [1, 3]

6. index()
- Syntax: [Link](item)
- Returns the index of the first occurrence of the specified item in the list.
colors = ["red", "green", "blue"]
index = [Link]("green") # 1

7. count()
- Syntax: [Link](item)
- Returns the number of times an item appears in the list.
numbers = [1, 2, 2, 3, 2, 4]
count = [Link](2) # 3

8. sort()
- Syntax: [Link]()
- Sorts the elements of the list in ascending order. (In-place sorting)
numbers = [3, 1, 2]
[Link]()
# numbers is now [1, 2, 3]

9. reverse()
- Syntax: [Link]()
- Reverses the order of elements in the list. (In-place reversal)
colors = ["red", "green", "blue"]
[Link]()
# colors is now ["blue", "green", "red"]

Populating Lists with Items:


 One of the popular way of populating lists is to start with an empty list [ ], then use the functions
append() or extend() to add items to the list.
 For example,
>>> continents = []
>>> [Link]("Asia")
>>> [Link]("Europe")
>>> [Link]("Africa")
>>> continents
['Asia', 'Europe', 'Africa']

Traversing a List:
- Traversing means iterating through the elements of a list.
- You can use a for loop to traverse a list.

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


for fruit in fruits:
print(fruit)

Output:
apple
banana
cherry

Nested lists:
 A list inside another list is called a nested list and you can get the behavior of nested lists in
Python by storing lists within the elements of another list.
 You can traverse through the items of nested lists using the for loop.
 The syntax for nested lists is,
Nested_list_name = [[item1,item2,item3],[item4,item5,item6],[item7,item8,item9]]

Nested List Example:

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


print("Nested List:", nested_list)
# Accessing elements in a nested list
element = nested_list[1][2]
print("Element at [1][2]:", element)

# Modifying an element in a nested list


nested_list[0][1] = 99
print("Modified Nested List:", nested_list)

Output:
Nested List: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Element at [1][2]: 6
Modified Nested List: [[1, 99, 3], [4, 5, 6], [7, 8, 9]]

The del statement:


 You can remove an item from a list based on its index rather than its value.
 The difference between del statement and pop() function is that the del statement does not return
any value while the pop() function returns a value.
 The del statement can also be used to remove slices from a list or clear the entire list.
 Examples:
>>> a = [5, -8, 99.99, 432, 108, 213]
>>> del a[0]
>>> a
[-8, 99.99, 432, 108, 213]
>>> del a[2:4]
>>> a
[-8, 99.99, 213]
>>> del a[:]
>>> a
[]

Program to implement stack operations:


stack=[]
stack_size=6

def display_stack():
if len(stack)>0:
print("At present items in the stack are:")
for i in range(len(stack)-1,-1,-1):
print(stack[i])
else:
print("Stack is empty.")

def push_stack(i):
print(f"Push item {i} to the stack.")
if len(stack)<stack_size:
[Link](i)
else:
print("Stack is full.")

def pop_stack():
if len(stack)>0:
print(f"Popped item is {[Link]()}")
else:
print("Stack is empty.")

def main():
push_stack(1)
push_stack(2)
push_stack(3)
display_stack()
pop_stack()
pop_stack()
display_stack()
push_stack(4)
push_stack(5)
push_stack(6)
push_stack(7)
push_stack(8)
push_stack(9)
display_stack()
pop_stack()
pop_stack()
pop_stack()
pop_stack()
pop_stack()
pop_stack()
pop_stack()
display_stack()

if __name__ == '__main__':
main()

# Push item 1 to the stack.


Push item 2 to the stack.
Push item 3 to the stack.
At present items in the stack are:
3
2
1
Popped item is 3
Popped item is 2
At present items in the stack are:
1
Push item 4 to the stack.
Push item 5 to the stack.
Push item 6 to the stack.
Push item 7 to the stack.
Push item 8 to the stack.
Push item 9 to the stack.
Stack is full.
At present items in the stack are:
8
7
6
5
4
1
Popped item is 8
Popped item is 7
Popped item is 6
Popped item is 5
Popped item is 4
Popped item is 1
Stack is empty.
Stack is empty.

Program to implement queue operations:


# Initialize an empty list to simulate a queue
queue = []

# Function to enqueue an element


def enqueue(item):
[Link](item)
print(f"Enqueued: {item}")

# Function to dequeue an element


def dequeue():
if not queue:
print("Queue is empty")
else:
front_element = [Link](0)
print(f"Dequeued: {front_element}")
return front_element

# Enqueue elements
enqueue("apple")
enqueue("banana")
enqueue("cherry")

# Dequeue an element
dequeued_element = dequeue()
# Print the current queue
print("Current queue:", queue)

Output:
Enqueued: apple
Enqueued: banana
Enqueued: cherry
Dequeued: apple
Current queue: ['banana', 'cherry']

Dictionaries:
Creating a dictionary:
 A dictionary is a collection of an unordered set of key:value pairs, with the requirement that the
keys are unique within a dictionary.
 Dictionaries are constructed using curly braces { }, wherein you include a list of key:value pairs
separated by commas.
 Also, there is a colon (:) separating each of these key and value pairs, where the words to the left
of the colon operator are the keys and the words to the right of the colon operator are the values.
 Unlike lists, which are indexed by a range of numbers, dictionaries are indexed by keys.
 Here a key along with its associated value is called a key:value pair. Dictionary keys are case
sensitive.
The syntax for creating a dictionary is,
dictionary_name = {key_1:value1,key_2:value2,…,key_n:valuen}
Example: alpha_num = {‘a’:1, ‘b’:2, ‘c’:3, ‘d’:4, ‘e’:5}

You can create an empty dictionary by specifying a pair of curly braces and without any key:value pairs.
The syntax is, dictionary_name = { }

For example,
>>> empty_dictionary = {}
>>> empty_dictionary
{}
>>> type(empty_dictionary)
<class 'dict'>

The dict() function:


The built-in dict() function is used to create dictionary.

The syntax for dict() function when the optional keyword arguments used is,
dict([**kwarg])

 The function dict() returns a new dictionary initialized from an optional keyword arguments and
a possibly empty set of keyword arguments.
 If no keyword argument is given, an empty dictionary is created.
 If keyword arguments are given, the keyword arguments and their values of the form kwarg =
value are added to the dictionary as key:value pairs.
>>> numbers = dict(one=1, two=2, three=3)
>>> numbers
{'one': 1, 'two': 2, 'three': 3}

The syntax for dict() function when iterables used is,


dict(iterable[, **kwarg])

 You can specify an iterable containing exactly two objects as tuple, the key and value in
the dict() function.
 For example,

>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])


{'sape': 4139, 'guido': 4127, 'jack': 4098}

Access and Modify key:value Pairs in Dictionaries:


 Each individual key:value pair in a dictionary can be accessed through keys by specifying it
inside square brackets.
 The key provided within the square brackets indicates the key:value pair being accessed.

The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]

The syntax for modifying the value of an existing key or for adding a new key:value pair
to a dictionary is,
dictionary_name[key] = value

 If the key is already present in the dictionary, then the key gets updated with the new value.
 If the key is not present then the new key:value pair gets added to the dictionary.

Examples:
>>> my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
>>> my_dict['name']
'John'
>>> my_dict['age']
25
>>> my_dict['city']
'New York'
>>> my_dict['age'] = 26
>>> my_dict['country'] = 'USA'
>>> my_dict
{'name': 'John', 'age': 26, 'city': 'New York', 'country': 'USA'}
Built-In Functions Used on Dictionaries
 len() - The len() function returns the number of items (key:value pairs) in a dictionary.
 all() - The all() function returns Boolean True value if all the keys in the dictionary are True else
returns False.
 any() - The any() function returns Boolean True value if any of the key in the dictionary is True
else returns False.
 sorted() - The sorted() function by default returns a list of items, which are sorted based on
dictionary keys.
Example:
>>> dict1={'a':1,'b':2,'c':3}
>>> len(dict1)
3
>>> dict2={0:'zero',1:'one',2:'two'}
>>> all(dict2)
False
>>> dict3={1:'one',2:'two'}
>>> all(dict3)
True
>>> dict4={'hith','eiffle','apple','fun'}
>>> sorted(dict4)
['apple', 'eiffle', 'fun', 'hith']

Dictionary Methods

Examples:
>>> my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
>>> my_dict.clear()
>>> my_dict
{}
>>> keys = ['name', 'age', 'city']
>>> default_value = 'Unknown'
>>> my_dict = [Link](keys, default_value)
>>> my_dict
{'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
>>> my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
>>> age_value = my_dict.get('age', 'Key not found')
>>> age_value
25
>>> my_dict.items()
dict_items([('name', 'John'), ('age', 25), ('city', 'New York')])
>>> my_dict.keys()
dict_keys(['name', 'age', 'city'])
>>> my_dict.pop('age')
25
>>> my_dict
{'name': 'John', 'city': 'New York'}
>>> my_dict.popitem()
('city', 'New York')
>>> my_dict
{'name': 'John'}
>>> my_dict = {'name': 'John', 'age': 25}
>>> my_dict.setdefault('city', 'Unknown')
'Unknown'
>>> my_dict
{'name': 'John', 'age': 25, 'city': 'Unknown'}
>>> dict1 = {'name': 'John', 'age': 25}
>>> dict2 = {'city': 'New York', 'country': 'USA'}
>>> [Link](dict2)
>>> dict1
{'name': 'John', 'age': 25, 'city': 'New York', 'country': 'USA'}
>>> my_dict.values()
dict_values(['John', 25, 'Unknown'])

Populating Dictionaries with key:value pairs:


 One of the common ways of populating dictionaries is to start with an empty dictionary { }, then
use the update() method to assign a value to the key using assignment operator.
 If the key does not exist, then the key:value pairs will be created automatically and added to the
dictionary.

>>> countries = {}
>>> [Link]({"Asia":"India"})
>>> [Link]({"Europe":"Germany"})
>>> [Link]({"Africa":"Sudan"})
>>> countries
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}

Python Program to Dynamically Build dictionary using User Input as a List.


def main():
print("Method 1: Building Dictionaries")
build_dictionary_1 = {}
for i in range(0, 2):
dic_key = input("Enter key: ")
dic_val = input("Enter value: ")
build_dictionary_1.update({dic_key: dic_val})
print(f"Dictionary is {build_dictionary_1}")

print("\nMethod 2: Building Dictionaries")


build_dictionary_2 = {}
for i in range(0, 2):
dic_key = input("Enter key: ")
dic_val = input("Enter value: ")
build_dictionary_2[dic_key] = dic_val
print(f"Dictionary is {build_dictionary_2}")

print("\nMethod 3: Building Dictionaries")


build_dictionary_3 = {}
i=0
while i < 2:
dict_key = input("Enter key: ")
dict_val = input("Enter value: ")
build_dictionary_3.update({dict_key: dict_val})
i += 1
print(f"Dictionary is {build_dictionary_3}")

if __name__ == "__main__":
main()

Output:
Method 1: Building Dictionaries
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Dictionary is {'a': '1', 'b': '2'}

Method 2: Building Dictionaries


Enter key: c
Enter value: 3
Enter key: d
Enter value: 4
Dictionary is {'c': '3', 'd': '4'}

Method 3: Building Dictionaries


Enter key: e
Enter value: 5
Enter key: f
Enter value: 6
Dictionary is {'e': '5', 'f': '6'}

Traversing of Dictionary:
 A for loop can be used to iterate over keys or values or key:value pairs in dictionaries.
 If you iterate over a dictionary using a for loop, then, by default, you will iterate over the
keys.
 If you want to iterate over the values, use values() method and for iterating over the key:value
pairs, specify the dictionary’s items() method explicitly.
 The dict_keys, dict_values, and dict_items data types returned by dictionary methods can be
used in for loops to iterate over the keys or values or key:value pairs.

Program to Illustrate Traversing of key:value Pairs in Dictionaries Using for Loop


currency = {"India": "Rupee", "USA": "Dollar", "Russia": "Ruble", "Japan": "Yen", "Germany":
"Euro"}
def main():
print("List of Countries")
for key in [Link]():
print(key)
print("List of Currencies in different Countries")
for value in [Link]():
print(value)
for key, value in [Link]():
print(f"'{key}' has a currency of type '{value}'")
if __name__ == "__main__":
main()

Output:

List of Countries
India
USA
Russia
Japan
Germany
List of Currencies in different Countries
Rupee
Dollar
Ruble
Yen
Euro
'India' has a currency of type 'Rupee'
'USA' has a currency of type 'Dollar'
'Russia' has a currency of type 'Ruble'
'Japan' has a currency of type 'Yen'
'Germany' has a currency of type 'Euro'
The del statement:
 To delete the key:value pair, use the del statement followed by the name of the dictionary along
with the key you want to delete.
del dict_name[key]

>>> countries = {'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}


>>> countries
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}
>>> del countries['Europe']
>>> countries
{'Asia': 'India', 'Africa': 'Sudan'}

Tuples and Sets

Tuples
 A tuple is a finite ordered list of values of possibly different types which is used to bundle related
values together without having to create a specific type to hold them.
 Tuples are immutable.
 Once a tuple is created, you cannot change its values.
 A tuple is defined by putting a comma-separated list of values inside parentheses ( ).
 Each value inside a tuple is called an item.
The syntax for creating tuples is,
Tuple_name = (item1,item2,…,itemn)
Example: t=(1,2,1.5,2.5,'a','b',"hello",(1,2),(3,4))
T1 = 1,2,3,4,5

Single value in a tuple: t =1, Output: (1,)

You can create an empty tuple without any values.


The syntax is,
tuple_name = ()
For example,
>>> empty_tuple = ()
>>> empty_tuple ()
>>> type(empty_tuple)
< class ‘tuple’>

The built-in tuple() function is used to create a tuple.


o tuple([sequence])
where the sequence can be a number, string or tuple itself.
Examples:
>>> a = "hello"
>>> string_to_tuple=tuple(a)
>>> string_to_tuple
('h', 'e', 'l', 'l', 'o')
>>> l=[1,2,3,4,5]
>>> list_to_tuple=tuple(l)
>>> list_to_tuple
(1, 2, 3, 4, 5)
>>> letters=('a','b','c')
>>> numbers=(1,2,3)
>>> nested_tuples=tuple((letters,numbers))
>>> nested_tuples
(('a', 'b', 'c'), (1, 2, 3))

If the optional sequence is not


specified, then an empty tuple is created.
o Empty tuple: Tuple=()

How to convert tuple into List? Give example.


To convert tuple into list, list() function is used as follows,
>>> a_tuple=(1,2,3,4,5)
>>> tuple_to_list=list(a_tuple)
>>> tuple_to_list
[1, 2, 3, 4, 5]

What is the output of


tuple = ( 'abcd', 786 , 2.23, 'john',70.2 )
print (tuple[1:3])

Output:
(786, 2.23)

Basic Tuple operations:


 + operator can be used to concatenate tuples together and the * operator to repeat a sequence of
tuple items.
Example:
>>> tuple1=(1,2,3,4,5)
>>> tuple2=(6,7,8,9,10)
>>> tuple1+tuple2
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
>>> tuple1 * 3
(1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5)

Membership operators (in and not in):


 You can check for the presence of an item in a tuple using in and not in membership operators.
 It returns a Boolean True or False.
Example:
>>> tuple1=(1,2,3,4,5)
>>> 1 in tuple1
True
>>> 6 in tuple1
False

Comparison operators
 Comparison operators like <, <=, >, >=, == and != are used to compare tuples.
Example:
>>> tuple1=(1,2,3,4,5)
>>> tuple2=(1,2,3,4,5)
>>> tuple3=(5,3,1,2,4)
>>> tuple4=(4,3,5,6)
>>> tuple1>tuple3
False
>>> tuple3>tuple1
True
>>> tuple1>=tuple3
False
>>> tuple1==tuple2
True
>>> tuple1<tuple3
True
>>> tuple1 != tuple2
False

Built-in functions used on Tuples:

There are many built-in functions for which a tuple can be passed as an argument.
 len() - The len() function returns the numbers of items in a tuple.
 sum() - The sum() function returns the sum of numbers in the tuple.
 sorted() - The sorted() function returns a sorted copy of the tuple as a list while leaving the
original tuple untouched.

Example:
>>> vowels=('a','e','i','o','u')
>>> len(vowels)
5
>>> values=(1,2,3,4,5)
>>> sum(values)
15
>>> a=(45,23,67,12)
>>> sorted(a)
[12, 23, 45, 67]

Indexing and Slicing in Tuples:


Indexing
 Each item in a tuple can be called individually through indexing.
 The expression inside the bracket is called the index.
 Square brackets [ ] are used by tuples to access individual items, with the first item at index 0,
the second item at index 1 and so on.
 The index provided within the square brackets indicates the value being accessed.

The syntax for accessing an item in a tuple is,


tuple_name[index]
where index should always be an integer value and indicates the item to be selected.
>>> fruits=('Apple','Banane','Cherry','Dragonfruit')
>>> fruits
('Apple', 'Banane', 'Cherry', 'Dragonfruit')
>>> fruits[0]
'Apple'
>>> fruits[3]
'Dragonfruit'
>>> fruits[5]
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
fruits[5]
IndexError: tuple index out of range

 In addition to positive index numbers, you can also access tuple items using a negative index
number, by counting backwards from the end of the tuple, starting at −1.
 Negative indexing is useful if you have a large number of items in the tuple and you want to
locate an item towards the end of a tuple.

>>> fruits=('Apple','Banane','Cherry','Dragonfruit')
>>> fruits
('Apple', 'Banane', 'Cherry', 'Dragonfruit')
>>> fruits[-2]
'Cherry'
>>> fruits[-1]
'Dragonfruit'

Slicing:
 Slicing of tuples is allowed in Python wherein a part of the tuple can be extracted by specifying
an index range along with the colon (:) operator, which itself results as tuple type.
 The syntax for tuple slicing is,
tuple_name[start:stop[:step]]

 start and stop are integer values (positive or negative values).


 Tuple slicing returns a part of the tuple from the start index value to stop index value, which
includes the start index value but excludes the stop index value.
 The step specifies the increment value to slice by and it is optional.

>>> colours=('v','i','b','g','y','o','r')
>>> colours[1:4]
('i', 'b', 'g')
>>> colours[:5]
('v', 'i', 'b', 'g', 'y')
>>> colours[3:]
('g', 'y', 'o', 'r')
>>> colours[:]
('v', 'i', 'b', 'g', 'y', 'o', 'r')
>>> colours[::]
('v', 'i', 'b', 'g', 'y', 'o', 'r')
>>> colours[1:5:2]
('i', 'g')
>>> colours[::2]
('v', 'b', 'y', 'r')
>>> colours[::-1]
('r', 'o', 'y', 'g', 'b', 'i', 'v')
>>> colours[-5:-2]
('b', 'g', 'y')

Tuple Methods:
 Various methods associated with tuple are
count() – Syntax - tuple_name.count(item). The count() method counts the number of times the item
has occurred in the tuple and returns it.
index() – Syntax - tuple_name.index(item). The index() method searches for the given item from the
start of the tuple and returns its index. If the value appears more than once, you will get the index of the
first one. If the item is not present in the tuple, then ValueError is thrown by this method.

Examples:
>>> a = ('a','b','c','r','t','a','s','a','u')
>>> [Link]('a')
3
>>> [Link]('c')
2
>>> [Link]('a')
0
>>> [Link]('x')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
[Link]('x')
ValueError: [Link](x): x not in tuple
Tuple Packing and Unpacking:
 The statement t = 12345, 54321, 'hello!' is an example of tuple packing.
>>> t = 12345, 54321, 'hello!'
>>> t
(12345, 54321, 'hello!')

 The reverse operation of tuple packing is also possible. For example,


>>> x, y, z = t
>>> x
12345
>>> y
54321
>>> z
'hello!
 This operation is called tuple unpacking and works for any sequence on the right-hand side.
 Tuple unpacking requires that there are as many variables on the left side of the equals sign as
there are items in the tuple

Traversing of Tuples:
 You can iterate through each item in tuples using for loop.
ocean_animals = ("electric_eel", "jelly_fish", "shrimp", "turtles", "blue_whale")
def main():
for each_animal in ocean_animals:
print(f"{each_animal} is an ocean animal")

if __name__ == "__main__":
main()

Output:
electric_eel is an ocean animal
jelly_fish is an ocean animal
shrimp is an ocean animal
turtles is an ocean animal
blue_whale is an ocean animal

Populating Tuples with items:


 You can populate tuples with items using += operator and also by converting list items to
tuple items.

Program to Populate Tuple with User input data

tuple_items = ()
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
user_input = int(input("Enter a number: "))
tuple_items += (user_input,)
print(f"Items added to tuple are {tuple_items}")

list_items = []
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
item = input("Enter an item to add: ")
list_items.append(item)
items_of_tuple = tuple(list_items)
print(f"Tuple items are {items_of_tuple}")

Output:
Enter the total number of items: 2
Enter a number: 23
Enter a number: 34
Items added to tuple are (23, 34)
Enter the total number of items: 3
Enter an item to add: 45
Enter an item to add: 56
Enter an item to add: 67
Tuple items are ('45', '56', '67')
Sets
A set is an unordered collection with no duplicate items. Primary uses of sets include membership
testing and eliminating duplicate entries. Sets also support mathematical operations, such as union,
intersection, difference, and symmetric difference.
Curly braces { } or the set() function can be used to create sets with a comma-separated list of items
inside curly brackets { }. Note: to create an empty set you have to use set() and not { } as the latter
creates an empty dictionary

Examples:
>>> basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)
{'pear', 'orange', 'banana', 'apple'}
>>> 'orange' in basket
True
>>> 'crabgrass' in basket
False
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a
{'d', 'a', 'b', 'r', 'c'}
>>> b
{'m', 'l', 'c', 'z', 'a'}
>>> a – b
{'b', 'r', 'd'}
>>> a | b
{'l', 'm', 'z', 'd', 'a', 'b', 'r', 'c'}
>>> a & b
{'a', 'c'}
>>> a ^ b
{'l', 'd', 'm', 'b', 'r', 'z'}
>>> len(basket)
4
>>> sorted(basket)
['apple', 'banana', 'orange', 'pear']

Set Methods:
Examples:
>>> fruits = {'Apple','Mango','Grapes','Orange','Banana'}
>>> vegies = {'Carrot','Tomato','Onion','Beetroot','Potato'}
>>> [Link]('Pineapple')
>>> fruits
{'Mango', 'Banana', 'Orange', 'Apple', 'Pineapple', 'Grapes'}
>>> european_flowers = {"sunflowers", "roses", "lavender", "tulips", "goldcrest"}
>>> american_flowers = {"roses", "tulips", "lilies", "daisies"}
>>> american_flowers.difference(european_flowers)
{'daisies', 'lilies'}
>>> american_flowers.intersection(european_flowers)
{'tulips', 'roses'}
>>> american_flowers.isdisjoint(european_flowers)
False
>>> american_flowers.issuperset(european_flowers)
False
>>> american_flowers.issubset(european_flowers)
False
>>> american_flowers.symmetric_difference(european_flowers)
{'daisies', 'goldcrest', 'lavender', 'sunflowers', 'lilies'}
>>> american_flowers.union(european_flowers)
{'daisies', 'roses', 'lavender', 'sunflowers', 'goldcrest', 'tulips', 'lilies'}
>>> american_flowers.update(european_flowers)
>>> american_flowers
{'daisies', 'roses', 'lavender', 'sunflowers', 'goldcrest', 'tulips', 'lilies'}
>>> american_flowers.discard("roses")
>>> american_flowers
{'daisies', 'lavender', 'sunflowers', 'goldcrest', 'tulips', 'lilies'}
>>> european_flowers.pop()
'tulips'
>>> american_flowers.clear()
>>> american_flowers
set()
Traversing of Sets:
You can iterate through each item in a set using a for loop.
Program:
warships = {"u.s.s._arizona", "hms_beagle", "ins_airavat", "ins_hetz"}
def main():
for each_ship in warships:
print(f"{each_ship} is a Warship")

if __name__ == "__main__":
main()

Output:
ins_hetz is a Warship
hms_beagle is a Warship
ins_airavat is a Warship
u.s.s._arizona is a Warship

Differentiate tuple and set datatype.


Tuple Set
Tuples are immutable, meaning their elements Sets are mutable, allowing for the addition and
cannot be changed or modified after the tuple is removal of elements. You can add new
created. Once a tuple is defined, you cannot elements or remove existing ones from a set.
add, remove, or modify elements.
Tuples are defined using parentheses ( ). Sets are defined using curly braces { }.
Elements are separated by commas. Elements are also separated by commas.
Example: my_tuple = (1, 2, 3) Example: my_set = {1, 2, 3}
Tuples can contain duplicate elements. Each Sets do not allow duplicate elements. If you try
element in a tuple is ordered and can be to add a duplicate element to a set, it will not
accessed by its index. raise an error, but the set will only contain
unique elements.
Elements are ordered and indexed Elements are unordered; no indexing

Give the output of the following Python code:


str1 = 'This is Python'
print( "Slice of String : ", str1[1 : 4 : 1] )
print ("Slice of String : ", str1[0 : -1 : 2] )

Output:
Slice of String : his
Slice of String : Ti sPto

Give the output of following Python code


newspaper = "new york times"
print(newspaper[0:12:4])
print (newspaper[::4])
Output:
ny
ny e

You might also like