UNIT 2 Python
UNIT 2 Python
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.
4. Empty strings. An empty string contains no characters and can be written as '' or "".
empty1 = ''
empty2 = ""
Output:
<class 'str'>
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’>
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
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
if 'apple' in fruit_list:
print("Found apple in the list.")
if 'world' in greeting:
print("Found 'world' in the greeting.")
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.")
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
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
- 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.
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
>>> 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).
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
You can specify a step value to skip characters when slicing. The syntax for this is:
substring = string[start:stop:step]
Output:
Pto rgamn
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:
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.
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!"
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****
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.
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, ...]
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
[]
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.
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
Output:
Combined List: [1, 2, 3, 4, 5, 6]
Repeated List: [1, 2, 3, 1, 2, 3, 1, 2, 3]
Syntax:
new_list = list(sequence)
Output:
['h', 'e', 'l', 'l', 'o']
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.
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']
Output:
Updated fruits: ['apple', 'grape', 'cherry']
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.
Output:
Number of fruits: 3
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"]
Traversing a List:
- Traversing means iterating through the elements of a list.
- You can use a for loop to traverse a list.
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]]
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]]
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()
# 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 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}
You can specify an iterable containing exactly two objects as tuple, the key and value in
the dict() function.
For example,
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'])
>>> countries = {}
>>> [Link]({"Asia":"India"})
>>> [Link]({"Europe":"Germany"})
>>> [Link]({"Africa":"Sudan"})
>>> countries
{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}
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'}
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.
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]
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
Output:
(786, 2.23)
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
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]
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]]
>>> 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!')
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
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
Output:
Slice of String : his
Slice of String : Ti sPto