0% found this document useful (0 votes)
4 views74 pages

Unit-2 Python (Full QB Solved) Final

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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)
4 views74 pages

Unit-2 Python (Full QB Solved) Final

Mangalore University lecturers prescribed answers

Uploaded by

Sindhoor J K
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

Unit- 2 Python(Question bank solved)

2m

1. Give two methods of creating strings in Python.

A string is a sequence of characters in Python. Strings can be created using single quotes, double quotes, or triple quotes. Two
common methods are using single quotes and double quotes.

Example:

greeting = 'Hello World'


book_title = "Python Programming"

2. List any two built-in functions used with python strings with their use.

Python provides many built-in functions for strings. The len() function is used to find the number of characters in a string. The
max() function returns the character with the highest ASCII/Unicode value.

Example:

text = "Python"

print(len(text)) # 6
print(max(text)) # y

3. Why are strings called immutable?

Strings are called immutable because once a string is created, its characters cannot be changed. Python does not allow direct
modification of string elements. Instead, a new string must be created.

Example:

immu = "dollar"
# immu[0] = 'c' → Error

new_word = "c" + immu[1:]


print(new_word)

Output:

collar

4. What is use of negative indexing? Give example.

Negative indexing is used to access characters from the end of a string or list. The index -1 represents the last character, -2
represents the second last character, and so on. It is useful when accessing elements from the end.

Example:

word_phrase = "be yourself"

print(word_phrase[-1])
print(word_phrase[-2])

Output:

f
l

5. How are membership operators used in strings?

Membership operators in and not in are used to check whether a substring exists in a string. They return True if the value is
found and False otherwise. These operators are commonly used in conditions.

Example:
greeting = "Hello world"

print('world' in greeting)
print('Python' not in greeting)

Output:

True
True

6. Give the output of the following Python code:

S = 'Python is easy'
print( "Slice of String : ", S[ : : 2] )
print ("Slice of String : ", S[-1: 5 :-1 ] )

Output:

Slice of String : Pto ses


Slice of String : ysae si

7. Give the syntax and example for split function.

The split() function is used to break a string into smaller parts and returns them as a list. The string is split based on a
separator. If no separator is given, whitespace is used by default.

Syntax:

string_name.split([separator [, maxsplit]])

Example:

inventors = "edison, tesla, marconi, newton"


print([Link](","))

Output:

['edison', ' tesla', ' marconi', ' newton']

8. Write the syntax of join function, give an example.

The join() method is used to combine multiple strings into a single string. A separator string is inserted between each element
of the sequence. All items in the sequence must be strings.

Syntax:

string_name.join(sequence)

Example:

words = ["This", "is", "a", "list"]

joined_string = " ".join(words)


print(joined_string)

Output:

This is a list

9. Write the python code to check given string is palindrome or not.

A palindrome is a string that reads the same forward and backward. In Python, it can be checked by comparing the original
string with its reverse. String slicing is used to reverse the string.

Program:

text = input("Enter a string: ")

if text == text[::-1]:
print("Palindrome")
else:
print("Not Palindrome")

10. What is list? How to create list?

A list is a collection of elements that are ordered and mutable. Lists can contain different data types such as numbers, strings,
and even other lists. Lists are created using square brackets [ ].

Example:

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


print(fruits)

Output:

['apple', 'banana', 'cherry']

11. List any four built-in functions used on list.

Python provides several built-in functions for lists. The len() function finds the number of elements, sum() calculates the total
of numeric values, sorted() sorts the list, and any() checks if at least one element is True.

Example:

numbers = [1, 2, 3, 4]

print(len(numbers))
print(sum(numbers))
print(sorted(numbers))
print(any([True, False]))

12. List the different basic operations performed on List.

Basic operations on lists include concatenation, repetition, indexing, slicing, and membership testing. Concatenation joins two
lists using +, while repetition repeats elements using *. Lists also support indexing and slicing to access elements.

Example:

list1 = [1, 2]
list2 = [3, 4]

print(list1 + list2)
print(list1 * 2)

Output:

[1, 2, 3, 4]
[1, 2, 1, 2]

13. Write any two List methods with their use.

The append() method adds an element at the end of the list. The insert() method inserts an element at a specified position in
the list. These methods are commonly used for modifying lists.

Example:

numbers = [1, 2, 3]

[Link](4)
[Link](1, 10)

print(numbers)

Output:

[1, 10, 2, 3, 4]
14. What is Nested List? Give example.

A nested list is a list that contains one or more lists as its elements. It is used to store data in a matrix-like structure. Nested
lists can be accessed using multiple indexes.

Example:

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

print(nested_list)
print(nested_list[1][2])

Output:

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


6

15. Write the output of the given python code:

aList = ['python', 'programming', 'is', 'Simple']


[Link] (2,'Not')
print(aList)

Output:

['python', 'programming', 'Not', 'is', 'Simple']

16. What is dictionary? Give example.

A dictionary is a collection of key:value pairs. Each key in a dictionary is unique and is used to access its corresponding value.
Dictionaries are created using curly braces { }.

Example:

student = {"name":"Ravi", "age":20, "course":"BCA"}

print(student)

Output:

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}

17. Write any two built-in functions in dictionary with their use.

The dict() function is used to create a dictionary. The len() function is used to find the number of key:value pairs in a
dictionary. These functions help in creating and managing dictionaries.

Example:

numbers = dict(one=1, two=2, three=3)

print(numbers)
print(len(numbers))

Output:

{'one': 1, 'two': 2, 'three': 3}


3

18. What is tuple? How it is created in Python?

A tuple is an ordered collection of elements in Python. Tuples are immutable, which means their elements cannot be changed
after creation. Tuples are created using parentheses ( ).

Example:
colors = ("red", "green", "blue")

print(colors)

Output:

('red', 'green', 'blue')

19. Differentiate between List and Tuple.

Lists are mutable, which means their elements can be modified after creation. Tuples are immutable and cannot be changed
once created. Lists use square brackets [ ] while tuples use parentheses ( ).

Example:

list1 = [1, 2, 3]
tuple1 = (1, 2, 3)

20. Write any two built-in function in tuple with their use.

The len() function is used to find the number of elements in a tuple. The max() function returns the largest element in the
tuple. These functions are commonly used with tuples.

Example:

numbers = (10, 20, 30, 40)

print(len(numbers))
print(max(numbers))

Output:

4
40

21. How to convert tuple into List? Give example.

A tuple can be converted into a list using the list() function. This is useful when we want to modify tuple elements because
lists are mutable.

Example:

tuple_data = (1, 2, 3)

list_data = list(tuple_data)

print(list_data)

Output:

[1, 2, 3]

22. What is packing and unpacking of tuple? Give example.

Tuple packing means storing multiple values into a single tuple. Tuple unpacking means extracting tuple elements into
separate variables. Python allows both operations easily.

Example:

# Packing
student = ("Ravi", 20, "BCA")

# Unpacking
name, age, course = student

print(name)
print(age)
print(course)

Output:

Ravi
20
BCA

23. What is set? How is it created in Python?

A set is an unordered collection of unique elements. Sets do not allow duplicate values and are useful for mathematical set
operations. Sets are created using curly braces { }.

Example:

numbers = {1, 2, 3, 4}

print(numbers)

24. List two set methods and mention the purpose of each method.

The add() method is used to add an element to a set. The remove() method is used to remove a specific element from a set.
These methods help in modifying set elements.

Example:

colors = {"red", "green"}

[Link]("blue")
[Link]("green")

print(colors)

Output:

{'red', 'blue'}

25. Differentiate tuple and set datatype.

A tuple is an ordered and immutable collection, while a set is unordered and mutable. Tuples allow duplicate values, but sets
store only unique elements. Tuples use ( ) whereas sets use { }.

Example:

tuple_data = (1, 2, 2, 3)
set_data = {1, 2, 2, 3}

print(tuple_data)
print(set_data)

Output:

(1, 2, 2, 3)
{1, 2, 3}

5 marks

[Link] is String? Explain how strings are created in Python with example.

A string is one of the most commonly used data types in Python. It is used to store and manipulate textual data such as
names, sentences, and messages.

A string is a sequence of characters enclosed within quotes.


In Python, characters can include letters, digits, symbols, and spaces.

Characteristics of Strings
• Strings are ordered (characters have index positions)

• Strings are immutable (cannot be changed after creation)

• Strings support indexing and slicing

• Strings can be created using different types of quotes

Methods of Creating Strings in Python

1. Using Single Quotes (' ')

Strings can be created using single quotation marks.

Example

s1 = 'Hello'
print(s1)

Output: Hello

2. Using Double Quotes (" ")

Strings can also be created using double quotation marks.

Example

s2 = "Python Programming"
print(s2)

Output: Python Programming

3. Using Triple Quotes (''' ''' or """ """)

Triple quotes are used to create multi-line strings or long text.

Example

s3 = '''Hello
Welcome to Python'''
print(s3)

Output:

Hello
Welcome to Python

4. Using str() Function

The str() function converts other data types into strings.

Example

num = 123
s4 = str(num)
print(s4)
print(type(s4))

Output:

123
<class 'str'>

5. Using Escape Characters

Strings can include special characters using escape sequences like \n, \t, etc.

Example
s5 = "Hello\nWorld"
print(s5)

Output:

Hello
World

6. Using String Concatenation

Strings can be created by combining two or more strings using +.

Example

s6 = "Hello" + " " + "Python"


print(s6)

Output: Hello Python

Important Points

• Strings can be created in multiple ways depending on requirement

• Quotes must match (start and end with same type)

• Strings are immutable, so modification creates a new string

Strings are fundamental in Python for handling text data. They can be created using single quotes, double quotes, triple
quotes, and functions like str(). Understanding string creation methods is essential for effective programming and text
manipulation.

[Link] the Basic operations performed on Strings.

A string is a sequence of characters enclosed within single quotes (' '), double quotes (" "), or triple quotes (''' '''). Python
provides several operations that can be performed on strings. These operations help in combining, comparing, accessing, and
manipulating string data. The basic operations performed on strings are:

1. Concatenation

2. Repetition

3. Membership Operators

4. String Comparison

5. Indexing

6. Slicing

7. Traversing Strings

1. Concatenation (+)

Concatenation means joining two or more strings together.


The + operator is used for concatenation. Python allows only strings to be concatenated with strings. If a number is to be
joined with a string, it must first be converted using str().

Syntax

string1 + string2

Example

s1 = "Hello"
s2 = "World"

print(s1 + " " + s2)

Output
Hello World

Example with Number Conversion

singer = str(50) + "cent"


print(singer)

Output

50cent

Explanation

Here, the number 50 is converted into a string using str() and then joined with "cent".

2. Repetition (*)

Repetition means repeating a string multiple times.


The * operator is used for repetition.

Syntax

string * number

Example

print("Hi! " * 3)

Output

Hi! Hi! Hi!

Explanation

The string "Hi! " is repeated 3 times.

3. Membership Operators (in and not in)

Membership operators are used to check whether a character or substring exists inside a string.
Python provides two membership operators:

• in

• not in

These operators return either True or False.

(a) in Operator

The in operator checks whether a value exists in a string.

Syntax

value in string

Example

greeting = "Hello World"

print("World" in greeting)
print("Python" in greeting)

Output

True
False

(b) not in Operator

The not in operator checks whether a value is not present in a string.


Syntax

value not in string

Example

greeting = "Python Programming"

print("Java" not in greeting)

Output

True

Explanation

Since "Java" is not present in the string, the output is True.

4. String Comparison

Strings can be compared using relational operators:

• ==

• !=

• <

• >

• <=

• >=

Comparison is done character by character based on ASCII/Unicode values.

Example

print("january" == "jane")
print("january" > "jane")
print("A" < "a")

Output

False
True
True

Explanation

Capital letters have smaller ASCII values than lowercase letters. Hence "A" < "a" is True.

5. Indexing

Indexing is used to access individual characters in a string.


Python uses 0-based indexing.

• First character → index 0

• Second character → index 1

Negative indexing is also allowed:

• -1 → last character

• -2 → second last character

Syntax

string[index]
Example

text = "Python"

print(text[0])
print(text[1])
print(text[-1])

Output

P
y
n

Explanation

text[0] gives the first character and text[-1] gives the last character.

6. String Slicing

String slicing is used to extract a part of a string.


It creates a new substring from the original string.

Syntax

string[start:stop]

• start → starting index (included)

• stop → ending index (excluded)

Example 1

text = "Python Programming"

print(text[0:6])

Output

Python

Example 2

print(text[7:])

Output

Programming

Example 3 (Using Step Value)

Syntax

string[start:stop:step]

Example

text = "Python Programming"

print(text[0:18:2])

Output

Pto rgamn

Explanation

The step value 2 skips every alternate character.

7. Traversing a String
Traversing means accessing each character of a string one by one.
It can be done using loops such as for loop or while loop.

Using for Loop

Syntax

for char in string:


statement

Example

text = "Python"

for char in text:


print(char, end=' ')

Output

Python

Explanation

The loop takes one character at a time from the string and prints it.

[Link] Indexing and Slicing on Strings with example.

A string is a sequence of characters stored in a specific order. In Python, characters in a string can be accessed using indexing
and slicing. These concepts are very important because they help us retrieve individual characters or parts of a string easily.

1. Indexing in Strings

Indexing means accessing individual characters of a string using their position number.
Python follows 0-based indexing, which means:

• First character → index 0

• Second character → index 1

• Third character → index 2

Python also supports negative indexing, where counting starts from the end of the string.

• Last character → -1

• Second last character → -2

Syntax of Indexing

string_name[index]

Where:

• string_name → Name of the string

• index → Position of the character

Example of Positive Indexing

text = "Python"

print(text[0])
print(text[1])
print(text[2])

Output

P
y
t
Explanation

• text[0] gives the first character P

• text[1] gives the second character y

• text[2] gives the third character t

Negative Indexing

Negative indexing is used to access characters from the end of the string.
It is useful when we want to access the last characters without knowing the exact length of the string.

Example of Negative Indexing

word_phrase = "be yourself"

print(word_phrase[-1])
print(word_phrase[-2])
print(word_phrase[-3])

Output

f
l
e

Explanation

• -1 represents the last character

• -2 represents the second last character

• -3 represents the third last character

Thus, indexing allows us to access characters from both beginning and end.

2. Slicing in Strings

String slicing is used to extract a part of a string.


It creates a new string from selected characters of the original string.

Slicing is very useful when we need only a portion of a string instead of the whole string.

Syntax of String Slicing

string_name[start:stop]

Where:

• start → Starting index (included)

• stop → Ending index (excluded)

Python includes the start index but excludes the stop index.

Example 1: Basic Slicing

text = "Python Programming"

substring1 = text[0:6]
print(substring1)

Output

Python

Explanation

• Slicing starts from index 0


• Stops before index 6

• Extracted string is "Python"

Example 2: Slicing from Middle to End

text = "Python Programming"

substring2 = text[7:]
print(substring2)

Output

Programming

Explanation

• Start index is 7

• Stop index is not given

• So slicing continues till the end of the string

Example 3: Slicing from Beginning

text = "Python Programming"

substring3 = text[:6]
print(substring3)

Output

Python

Explanation

• Start index is not given

• Python automatically starts from index 0

• Stops before index 6

Slicing with Step Value

Python allows slicing with a step value.


Step value means how many positions to skip while extracting characters.

Syntax

string_name[start:stop:step]

Where:

• step → Number of positions to move

Example

text = "Python Programming"

substring = text[0:18:2]
print(substring)

Output

Pto rgamn

Explanation

• Starts from index 0


• Stops before index 18

• Takes every 2nd character

Slicing Using Negative Indexing

Negative indexing can also be used in slicing.

Example 1

text = "Python Programming"

print(text[-11:-1])

Output

Programmin

Explanation

• Starts 11 characters from the end

• Stops before the last character

Example 2

print(text[-5:])

Output

mming

Explanation

• Starts from the 5th character from the end

• Continues till the end

Reversing a String Using Slicing

A string can also be reversed using slicing with negative step value.

Example

text = "Python"

print(text[::-1])

Output

nohtyP

Explanation

• Step value -1 moves backward

• Hence the string gets reversed

[Link] with example the following string methods

i) Join ii) Split

String methods in Python are built-in functions that help in performing different operations on strings. Among them, join()
and split() are very important methods used for combining and separating strings. These methods are widely used in text
processing and data handling.

1. split() Method

The split() method is used to break a string into smaller parts.


It divides the string based on a separator and returns the result as a list.
If no separator is specified, Python uses whitespace (space) as the default separator.

Syntax of split()

string_name.split([separator [, maxsplit]])

Explanation

• separator → Character used to split the string (optional)

• maxsplit → Maximum number of splits (optional)

If maxsplit is not specified, Python performs all possible splits.

Example 1: Using Separator

inventors = "edison, tesla, marconi, newton"

print([Link](","))

Output

['edison', ' tesla', ' marconi', ' newton']

Explanation

The string is divided wherever a comma , appears.


The result is returned as a list of strings.

Example 2: Without Separator

watches = "rolex hublot cartier omega"

print([Link]())

Output

['rolex', 'hublot', 'cartier', 'omega']

Explanation

No separator is given, so Python automatically uses whitespace (space) to split the string.

Example 3: Using maxsplit

text = "apple banana mango orange"

print([Link](" ", 2))

Output

['apple', 'banana', 'mango orange']

Explanation

• The separator is space " "

• maxsplit = 2

• Only two splits are performed

• Therefore, the output contains maxsplit + 1 items

Important Points about split()

1. split() breaks a string into smaller strings

2. It returns the result as a list

3. Separator can be comma, space, colon, etc.


4. Default separator is whitespace

5. maxsplit limits the number of splits

2. join() Method

The join() method is used to combine multiple strings into one string.
It inserts a specified separator between the elements of a sequence.

The sequence can be:

• List

• Tuple

• String

All elements must be strings.

Syntax of join()

string_name.join(sequence)

Explanation

• string_name → Separator inserted between elements

• sequence → Collection of strings

Example 1: Joining List Elements

words = ["This", "is", "a", "list"]

joined_string = " ".join(words)

print(joined_string)

Output

This is a list

Explanation: A space " " is inserted between each word in the list.

Example 2: Using Different Separator

words = ["This", "is", "a", "list"]

new_string = ":".join(words)

print(new_string)

Output

This:is:a:list

Explanation: The colon : is inserted between each element of the list.

Example 3: Joining Characters of a String

numbers = "123"
characters = "amy"

password = [Link](characters)

print(password)

Output

a123m123y
Explanation: The string "123" is inserted between each character of "amy".

Important Points about join()

1. join() combines multiple strings into one string

2. It inserts a separator between elements

3. The sequence may be a list, tuple, or string

4. All elements must be strings

5. It is faster and more efficient than repeated concatenation

[Link] any Five String methods with syntax and example.

Python provides many built-in string methods that are used to perform different operations on strings. String methods help in
modifying, searching, formatting, and processing text easily. These methods are very useful in Python programming and text
manipulation.

The following are some important string methods:

1. upper()

2. lower()

3. replace()

4. split()

5. join()

Additional methods:
6. strip()
7. find()

1. upper() Method

The upper() method converts all lowercase letters of a string into uppercase letters.
It returns a new string and does not change the original string.

Syntax

string_name.upper()

Example

text = "python programming"

print([Link]())

Output

PYTHON PROGRAMMING

Explanation: All lowercase characters in the string are converted into uppercase letters.

2. lower() Method

The lower() method converts all uppercase letters of a string into lowercase letters.

Syntax

string_name.lower()

Example

text = "PYTHON PROGRAMMING"

print([Link]())
Output

python programming

Explanation: All uppercase letters are converted into lowercase letters.

3. replace() Method

The replace() method is used to replace one substring with another substring in a string.

Syntax

string_name.replace(old, new)

Where:

• old → Existing substring

• new → New substring to replace with

Example

text = "Python is easy"

print([Link]("easy", "powerful"))

Output

Python is powerful

Explanation: The word "easy" is replaced with "powerful".

4. split() Method

The split() method is used to divide a string into smaller parts.


It returns the result as a list.

Syntax

string_name.split(separator)

Example

inventors = "edison, tesla, marconi, newton"

print([Link](","))

Output

['edison', ' tesla', ' marconi', ' newton']

Explanation: The string is split wherever a comma appears.

5. join() Method

The join() method is used to combine multiple strings into one string using a separator.

Syntax

[Link](sequence)

Example

words = ["This", "is", "a", "list"]

joined_string = " ".join(words)

print(joined_string)

Output
This is a list

Explanation: A space " " is inserted between each word and all words are combined into one string.

6. strip() Method

The strip() method removes spaces or unwanted characters from the beginning and end of a string.

Syntax

string_name.strip()

Example

text = " Python "

print([Link]())

Output

Python

Explanation

Leading and trailing spaces are removed from the string.

7. find() Method

The find() method searches for a substring inside a string and returns its index position.
If the substring is not found, it returns -1.

Syntax

string_name.find(substring)

Example

text = "Python Programming"

print([Link]("Program"))

Output

Explanation

The substring "Program" starts at index position 7.

[Link] why Strings are immutable? Write the two reasons why string objects are made immutable in Python.

In Python, a string is a sequence of characters enclosed within single quotes, double quotes, or triple quotes. Strings are one
of the most commonly used data types in Python. An important feature of strings is that they are immutable.

The word immutable means “cannot be changed.”


Once a string is created in Python, its contents cannot be modified [Link] any modification is required, Python creates a
completely new string instead of changing the original string.

Example Showing String Immutability

word = "dollar"

word[0] = "c"

Output

TypeError: 'str' object does not support item assignment

Explanation
In the above program, Python gives an error because strings do not allow modification of characters using indexing.

Correct Way to Modify a String

Since strings are immutable, a new string must be created.

word = "dollar"

new_word = "c" + word[1:]

print(new_word)

Output

collar

Explanation

The original string "dollar" is not changed.


Python creates a new string "collar".

Reasons Why Strings are Immutable in Python

Python makes string objects immutable for several important reasons.


The two major reasons are:

1. Security and Data Integrity

2. Memory Optimization and Performance

1. Security and Data Integrity

Immutability makes strings safer because their values cannot be changed accidentally during program execution.
This helps maintain the correctness and reliability of data.

When strings are used as:

• passwords

• usernames

• file names

• keys in dictionaries

their values should remain unchanged.

If strings were mutable, important data could be modified unintentionally, causing errors and security problems.

Example

password = "Admin123"

# password[0] = "a" → Not allowed

Explanation: Python prevents modification of the string to protect data integrity.

2. Memory Optimization and Performance

Python uses a technique called string interning to save memory.


If two variables contain the same string value, Python stores only one copy of that string in memory.

This is possible only because strings are immutable.

Example

s1 = "Python"
s2 = "Python"
print(id(s1))
print(id(s2))

Output

Same memory address is displayed

Explanation

Both variables point to the same memory location because the string value cannot be changed.

This saves memory and improves program performance.

[Link] is List? Explain the different ways to create List in Python.

A list is one of the most important data structures in Python.


A list is an ordered collection of elements enclosed within square brackets [ ]. Lists are used to store multiple values in a single
variable.

The elements in a list can be: numbers ,strings ,characters ,mixed data types ,other lists .

Lists are mutable, which means their elements can be changed after creation.

Syntax of List

list_name = [element1, element2, element3]

Example of List

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

print(fruits)

Output

['apple', 'banana', 'mango']

Different Ways to Create List in Python

Lists can be created in different ways in Python.


Some important methods are:

1. Creating Empty List

2. Creating List with Elements

3. Using list() Constructor

4. Creating List using range() Function

5. Creating Nested List

6. Creating List using User Input

7. Creating List using String split() Method

1. Creating Empty List

An empty list is a list without elements.


It can be created using square brackets [ ].

Syntax

list_name = []

Example

empty_list = []

print(empty_list)
Output

[]

Explanation: The list contains no elements.

2. Creating List with Elements

A list can be created by placing elements inside square brackets separated by commas.

Example

numbers = [10, 20, 30, 40]

print(numbers)

Output

[10, 20, 30, 40]

Example with Mixed Data Types

mixed_list = [101, "Python", 98.5, True]

print(mixed_list)

Output

[101, 'Python', 98.5, True]

Explanation: Lists can store different data types together.

3. Creating List using list() Constructor

Python provides a built-in list() function to create lists.

Syntax

list_name = list(iterable)

Example

letters = list("Python")

print(letters)

Output

['P', 'y', 't', 'h', 'o', 'n']

Explanation: The string "Python" is converted into a list of characters.

4. Creating List using range() Function

The range() function generates a sequence of numbers, and list() converts it into a list.

Syntax

list(range(start, stop, step))

Example

numbers = list(range(1, 11))

print(numbers)

Output

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

Example with Step Value


even_numbers = list(range(2, 11, 2))

print(even_numbers)

Output

[2, 4, 6, 8, 10]

Explanation: The step value 2 generates even numbers.

5. Creating Nested List

A nested list is a list containing one or more lists inside it.

Example

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

print(nested_list)

Output

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

Explanation: Each element of the main list is itself another list.

6. Creating List using User Input

Lists can also be created by taking values from the user.

Example

numbers = []

for i in range(3):
value = int(input("Enter number: "))
[Link](value)

print(numbers)

Explanation: The append() method adds user-entered values to the list.

7. Creating List using split() Method

The split() method converts a string into a list.

Example

text = "apple banana mango"

fruit_list = [Link]()

print(fruit_list)

Output

['apple', 'banana', 'mango']

Explanation: The string is divided at spaces and converted into a list.

[Link] the Basic operations performed on Lists with example.

A list is one of the most commonly used data structures in Python.


A list is an ordered and mutable collection of elements enclosed within square brackets [ ].

Python allows several operations to be performed on lists. These operations help in accessing, combining, modifying, and
processing list elements easily.

The basic operations performed on lists are:


1. Concatenation

2. Repetition

3. Membership Operators

4. List Comparison

5. Indexing

6. Slicing

7. Traversing Lists

1. Concatenation (+)

Concatenation means combining two or more lists into a single list.


The + operator is used for concatenation.

Syntax

list1 + list2

Example

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

print(list1 + list2)

Output

[1, 2, 3, 4, 5, 6]

Explanation: The elements of list1 and list2 are combined into a new list.

2. Repetition (*)

Repetition means repeating the elements of a list multiple times.


The * operator is used for repetition.

Syntax

list * number

Example

numbers = [1, 2, 3]

print(numbers * 3)

Output

[1, 2, 3, 1, 2, 3, 1, 2, 3]

Explanation

The list elements are repeated three times.

3. Membership Operators (in and not in)

Membership operators are used to check whether an element exists in a list.

Python provides:

• in

• not in

These operators return either True or False.


(a) in Operator

The in operator checks whether an element is present in the list.

Syntax

element in list

Example

numbers = [10, 20, 30, 40]

print(20 in numbers)
print(50 in numbers)

Output

True
False

Explanation

• 20 exists in the list

• 50 does not exist in the list

(b) not in Operator

The not in operator checks whether an element is absent from the list.

Example

numbers = [10, 20, 30]

print(40 not in numbers)

Output

True

Explanation

Since 40 is not present in the list, the result is True.

4. List Comparison

Lists can be compared using relational operators such as:

• ==

• !=

• <

• >

• <=

• >=

Comparison is done element by element.

Example

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

print(list1 == list2)
print(list1 != list3)
Output

True
True

Explanation

• list1 and list2 contain the same elements

• list1 and list3 are different

5. Indexing

Indexing is used to access individual elements of a list.


Python follows 0-based indexing.

• First element → index 0

• Second element → index 1

Negative indexing is also supported.

Syntax

list_name[index]

Example

colors = ["red", "green", "blue"]

print(colors[0])
print(colors[1])
print(colors[-1])

Output

red
green
blue

Explanation

• colors[0] gives first element

• colors[-1] gives last element

6. Slicing

Slicing is used to extract a part of a list.


It creates a new list from selected elements.

Syntax

list_name[start:stop]

Where:

• start → Starting index (included)

• stop → Ending index (excluded)

Example 1

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output

[20, 30, 40]


Explanation

Elements from index 1 to 3 are extracted.

Slicing with Step Value

Syntax

list_name[start:stop:step]

Example 2

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

print(numbers[0:6:2])

Output

[1, 3, 5]

Explanation

The step value 2 selects every alternate element.

7. Traversing a List

Traversing means accessing each element of the list one by one.


This can be done using loops such as for loop and while loop.

Using for Loop

Syntax

for variable in list:


statements

Example

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

for item in fruits:


print(item)

Output

apple
banana
mango

Explanation: The loop takes one element at a time from the list and prints it.

[Link] Indexing and Slicing on List with example.

A list is an ordered and mutable collection of elements enclosed within square brackets [ ].
In Python, elements of a list can be accessed using indexing and slicing. These operations help in retrieving individual
elements or extracting parts of a list easily.

Indexing and slicing are very important operations performed on lists in Python programming.

1. Indexing on Lists

Indexing is used to access individual elements of a list using their position number.

Python follows 0-based indexing, which means:

• First element → index 0

• Second element → index 1

• Third element → index 2


Python also supports negative indexing, where counting starts from the end.

• Last element → -1

• Second last element → -2

Syntax of Indexing

list_name[index]

Where:

• list_name → Name of the list

• index → Position number of the element

Example of Positive Indexing

colors = ["red", "green", "blue", "yellow"]

print(colors[0])
print(colors[1])
print(colors[2])

Output

red
green
blue

Explanation

• colors[0] returns the first element "red"

• colors[1] returns the second element "green"

• colors[2] returns the third element "blue"

Negative Indexing

Negative indexing is used to access elements from the end of the list.

Example

numbers = [10, 20, 30, 40, 50]

print(numbers[-1])
print(numbers[-2])
print(numbers[-3])

Output

50
40
30

Explanation

• -1 refers to the last element

• -2 refers to the second last element

• -3 refers to the third last element

Updating List Elements using Indexing

Lists are mutable, so elements can be modified using indexing.

Example
numbers = [10, 20, 30]

numbers[1] = 50

print(numbers)

Output

[10, 50, 30]

Explanation

The element at index 1 is changed from 20 to 50.

2. Slicing on Lists

Slicing is used to extract a portion of a list.


It creates a new list from selected elements of the original list.

Syntax of List Slicing

list_name[start:stop]

Where:

• start → Starting index (included)

• stop → Ending index (excluded)

Example 1: Basic Slicing

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

Output

[20, 30, 40]

Explanation

Elements from index 1 to 3 are extracted.


The stop index 4 is excluded.

Example 2: Slicing from Beginning

numbers = [10, 20, 30, 40, 50]

print(numbers[:3])

Output

[10, 20, 30]

Explanation

• Start index is not given

• Python automatically starts from index 0

Example 3: Slicing till End

numbers = [10, 20, 30, 40, 50]

print(numbers[2:])

Output

[30, 40, 50]


Explanation

• Slicing starts from index 2

• Continues till the end of the list

Slicing with Step Value

Python allows slicing with a step value.


The step value determines how many positions to skip.

Syntax

list_name[start:stop:step]

Example

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

print(numbers[0:8:2])

Output

[1, 3, 5, 7]

Explanation

The step value 2 selects every alternate element.

Slicing using Negative Indexing

Negative indexing can also be used in slicing.

Example

numbers = [10, 20, 30, 40, 50]

print(numbers[-4:-1])

Output

[20, 30, 40]

Explanation

• Starts from the 4th element from the end

• Stops before the last element

Reversing a List using Slicing

A list can be reversed using slicing with a negative step value.

Example

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

print(numbers[::-1])

Output

[5, 4, 3, 2, 1]

Explanation

The step value -1 moves backward and reverses the list.

Advantages of Indexing and Slicing

1. Easy access to list elements


2. Helps extract required portions of data

3. Supports both positive and negative indexing

4. Useful in data manipulation

5. Makes list processing efficient

[Link] syntax and example, any three built in functions on Lists.

Python provides several built-in functions that can be used on lists. These functions help in performing operations such as
finding the length of the list, calculating values, sorting elements, and checking conditions. Built-in functions make list
handling easy and efficient.

Some commonly used built-in functions on lists are:

1. len()

2. sum()

3. max()

4. min()

5. sorted()

6. any()

7. all()

1. len() Function

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

Syntax

len(list_name)

Example

numbers = [10, 20, 30, 40, 50]

print(len(numbers))

Output

Explanation

The list contains 5 elements, so the function returns 5.

2. sum() Function

The sum() function is used to calculate the total sum of all numeric elements in a list.

Syntax

sum(list_name)

Example

numbers = [10, 20, 30, 40]

print(sum(numbers))

Output

100

Explanation
The function adds all elements:
10 + 20 + 30 + 40 = 100

3. max() Function

The max() function returns the largest element in the list.

Syntax

max(list_name)

Example

numbers = [25, 10, 45, 5, 30]

print(max(numbers))

Output

45

Explanation

Among all the elements, 45 is the largest value.

4. min() Function

The min() function returns the smallest element in the list.

Syntax

min(list_name)

Example

numbers = [25, 10, 45, 5, 30]

print(min(numbers))

Output

Explanation: Among all elements, 5 is the smallest value.

5. sorted() Function

The sorted() function is used to sort the elements of a list in ascending order.
It returns a new sorted list.

Syntax

sorted(list_name)

Example

numbers = [40, 10, 30, 20]

print(sorted(numbers))

Output

[10, 20, 30, 40]

Explanation: The elements are arranged in ascending order.

Sorting in Descending Order


numbers = [40, 10, 30, 20]

print(sorted(numbers, reverse=True))

Output

[40, 30, 20, 10]

6. any() Function

The any() function returns True if at least one element in the list is true.

Syntax

any(list_name)

Example

values = [0, False, 10]

print(any(values))

Output

True

Explanation

Since 10 is a true value, the function returns True.

7. all() Function

The all() function returns True only if all elements in the list are true.

Syntax

all(list_name)

Example

values = [1, 2, 3]

print(all(values))

Output

True

Explanation

All elements are non-zero and true values, so the result is True.

[Link] any five List methods with syntax and their purpose.

Python provides many built-in methods for performing operations on lists.


List methods are special functions associated with lists that help in adding, removing, modifying, and arranging elements in a
list.

List methods are very important because lists are mutable, which means their contents can be changed after creation.

Some commonly used list methods are:

1. append()

2. insert()

3. remove()

4. pop()

5. sort()
Additional useful methods:
6. extend()
7. reverse()

1. append() Method

The append() method is used to add an element at the end of the list.

Syntax

list_name.append(element)

Example

numbers = [10, 20, 30]

[Link](40)

print(numbers)

Output

[10, 20, 30, 40]

Purpose

• Adds a new element to the end of the list

• Used when elements need to be added dynamically

2. insert() Method

The insert() method is used to insert an element at a specified position in the list.

Syntax

list_name.insert(index, element)

Where:

• index → Position where element is inserted

• element → Value to be inserted

Example

colors = ["red", "blue", "yellow"]

[Link](1, "green")

print(colors)

Output

['red', 'green', 'blue', 'yellow']

Purpose

• Inserts elements at a required position

• Useful for maintaining order in lists

3. remove() Method

The remove() method is used to delete a specified element from the list.

Syntax

list_name.remove(element)
Example

numbers = [10, 20, 30, 40]

[Link](20)

print(numbers)

Output

[10, 30, 40]

Purpose

• Removes a specific element from the list

• Useful for deleting unwanted data

4. pop() Method

The pop() method removes and returns an element from the list.
If no index is specified, it removes the last element.

Syntax

list_name.pop(index)

Example 1: Without Index

numbers = [10, 20, 30, 40]

[Link]()

print(numbers)

Output

[10, 20, 30]

Example 2: With Index

numbers = [10, 20, 30, 40]

[Link](1)

print(numbers)

Output

[10, 30, 40]

Purpose

• Removes elements from a specific position

• Returns the removed element

• Useful in stack operations

5. sort() Method

The sort() method is used to arrange list elements in ascending order.

Syntax

list_name.sort()

Example
numbers = [40, 10, 30, 20]

[Link]()

print(numbers)

Output

[10, 20, 30, 40]

Purpose

• Arranges elements in ascending order

• Useful for searching and organizing data

Sorting in Descending Order

numbers = [40, 10, 30, 20]

[Link](reverse=True)

print(numbers)

Output

[40, 30, 20, 10]

6. extend() Method (Additional Method)

The extend() method is used to add elements of one list to another list.

Syntax

[Link](list2)

Example

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

[Link](list2)

print(list1)

Output

[1, 2, 3, 4, 5, 6]

Purpose

• Combines elements of two lists

• Useful for merging lists

7. reverse() Method (Additional Method)

The reverse() method reverses the order of elements in a list.

Syntax

list_name.reverse()

Example

numbers = [1, 2, 3, 4]

[Link]()
print(numbers)

Output

[4, 3, 2, 1]

Purpose

• Reverses list order

• Useful in data processing and algorithms

[Link] is Dictionary? Explain the different ways to create Dictionary in Python.

A dictionary is an unordered collection of elements stored in the form of key:value pairs enclosed within curly braces { }.

It is one of the important built-in data types in Python.

In a dictionary:

• Each key is unique

• Keys are used to access values

• Values can be of any datatype

Dictionaries are mutable, which means their elements can be modified after creation.

Features of Dictionary

1. Stores data as key:value pairs

2. Keys must be unique

3. Values can be duplicated

4. Dictionaries are mutable

5. Elements are enclosed within { }

Syntax of Dictionary

dictionary_name = {
key1 : value1,
key2 : value2,
key3 : value3
}

Example of Dictionary

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

print(student)

Output

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}

Explanation

• "name", "age", and "course" are keys

• "Ravi", 20, and "BCA" are values

Python provides different ways to create dictionaries.


1. Creating Dictionary using Curly Braces { }

A dictionary can be created by directly placing key:value pairs inside curly braces.

Syntax

dictionary_name = {key1:value1, key2:value2}

Example

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

print(my_dict)

Output

{'name': 'John', 'age': 25, 'city': 'New York'}

Explanation

• 'name', 'age', and 'city' are keys.

• 'John', 25, and 'New York' are values.

2. Creating Dictionary using dict() Function with Keyword Arguments

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


When keyword arguments are used, each keyword becomes a key and its value becomes the dictionary value.

Syntax

dict([**kwarg])

Example

numbers = dict(one=1, two=2, three=3)

print(numbers)

Output

{'one': 1, 'two': 2, 'three': 3}

Explanation: The keyword arguments one=1, two=2, and three=3 are converted into key:value pairs.

3. Creating Dictionary using dict() Function with Iterable

The dict() function can also take an iterable containing tuples.


Each tuple must contain exactly two elements:

• first element → key

• second element → value

Syntax

dict(iterable)

Example

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

print(student)

Output

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

Explanation: Each tuple inside the list becomes a key:value pair in the dictionary.

4. Creating Empty Dictionary


An empty dictionary can be created using { }.

Syntax

dictionary_name = {}

Example

countries = {}

print(countries)

Output

{}

Explanation: The dictionary contains no key:value pairs.

5. Populating Dictionary using update() Method

One common way of creating dictionaries is to start with an empty dictionary and then use the update() method to add
key:value pairs.

Example

countries = {}

[Link]({"Asia":"India"})
[Link]({"Europe":"Germany"})
[Link]({"Africa":"Sudan"})

print(countries)

Output

{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}

Explanation: The update() method adds new key:value pairs to the dictionary.

6. Creating Dictionary using Assignment Operator

A dictionary can also be built dynamically by assigning values to keys.

Example

build_dictionary = {}

build_dictionary["name"] = "Ravi"
build_dictionary["course"] = "BCA"

print(build_dictionary)

Output

{'name': 'Ravi', 'course': 'BCA'}

Explanation

• If the key does not exist, Python automatically creates the key:value pair.

• If the key already exists, the value gets updated.

7. Creating Dictionary using User Input

Dictionaries can be dynamically created using user input.


The document shows building dictionaries using loops and update() method.

Example
build_dictionary = {}

for i in range(0, 2):


dic_key = input("Enter key: ")
dic_val = input("Enter value: ")

build_dictionary.update({dic_key: dic_val})

print(build_dictionary)

Sample Output

Enter key: a
Enter value: 1
Enter key: b
Enter value: 2

{'a': '1', 'b': '2'}

Explanation: The user enters keys and values, which are added dynamically to the dictionary.

[Link] syntax and example, any three built in functions on Dictionary.

Python provides several built-in functions that can be used on dictionaries.


These functions help in finding the length of the dictionary, converting data into dictionaries, checking values, and performing
various operations easily.

1. len()

2. dict()

3. str()

Additional related functions mentioned and used with dictionaries:


4. type()
5. sorted()

1. len() Function

The len() function is used to find the number of key:value pairs present in a dictionary.

Syntax

len(dictionary_name)

Example

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

print(len(student))

Output

Explanation: The dictionary contains three key:value pairs, so the function returns 3.

2. dict() Function

The dict() function is used to create a dictionary.


The document explains that dict() can create dictionaries using:
• keyword arguments

• iterable objects containing tuples

Syntax

dict([**kwarg])

OR

dict(iterable)

Example 1: Using Keyword Arguments

numbers = dict(one=1, two=2, three=3)

print(numbers)

Output

{'one': 1, 'two': 2, 'three': 3}

Example 2: Using Iterable

student = dict([('sape', 4139), ('guido', 4127)])

print(student)

Output

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

Explanation

The dict() function converts tuples into key:value pairs.

3. str() Function

The str() function converts a dictionary into a string representation.

Syntax

str(dictionary_name)

Example

student = {
"name": "Ravi",
"age": 20
}

result = str(student)

print(result)
print(type(result))

Output

{'name': 'Ravi', 'age': 20}


<class 'str'>

Explanation: The dictionary is converted into string format.

4. type() Function (Additional Function)

The type() function is used to identify the datatype of an object.

Syntax

type(object)
Example

student = {
"name": "Ravi",
"age": 20
}

print(type(student))

Output

<class 'dict'>

Explanation: The function shows that the object belongs to dictionary datatype.

5. sorted() Function (Additional Function)

The sorted() function sorts the keys of the dictionary in ascending order.

Syntax

sorted(dictionary_name)

Example

student = {
"course": "BCA",
"age": 20,
"name": "Ravi"
}

print(sorted(student))

Output

['age', 'course', 'name']

Explanation: The dictionary keys are sorted alphabetically.

[Link] any five Dictionary methods with syntax and their purpose.

Python provides many built-in methods for performing operations on dictionaries.


Dictionary methods help in adding, deleting, accessing, and modifying key:value pairs easily.

Since dictionaries are mutable, these methods are very useful in dictionary manipulation and data processing.

1. keys()

2. values()

3. items()

4. update()

5. get()

Additional methods from the document:


6. pop()
7. clear()

1. keys() Method

The keys() method returns all the keys present in the dictionary.

Syntax

dictionary_name.keys()

Example
student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

print([Link]())

Output

dict_keys(['name', 'age', 'course'])

Purpose

• Used to access all dictionary keys

• Helpful in traversing dictionary elements

2. values() Method

The values() method returns all the values present in the dictionary.

Syntax

dictionary_name.values()

Example

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

print([Link]())

Output

dict_values(['Ravi', 20, 'BCA'])

Purpose

• Used to access all dictionary values

• Useful for displaying stored data

3. items() Method

The items() method returns both keys and values together in tuple form.

Syntax

dictionary_name.items()

Example

student = {
"name": "Ravi",
"age": 20
}

print([Link]())

Output

dict_items([('name', 'Ravi'), ('age', 20)])

Purpose
• Returns key:value pairs together

• Useful in loops and traversal operations

4. update() Method

The update() method is used to add new key:value pairs or modify existing values in a dictionary.
The document also uses this method while populating dictionaries.

Syntax

dictionary_name.update({key:value})

Example

student = {
"name": "Ravi",
"age": 20
}

[Link]({"course":"BCA"})

print(student)

Output

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}

Explanation: A new key:value pair "course":"BCA" is added.

Example of Updating Existing Value

student = {
"name": "Ravi",
"age": 20
}

[Link]({"age":21})

print(student)

Output

{'name': 'Ravi', 'age': 21}

Purpose

• Adds new elements

• Modifies existing values

• Useful for dynamic dictionary creation

5. get() Method

The get() method returns the value associated with a specified key.
It avoids errors if the key is not present.

Syntax

dictionary_name.get(key)

Example

student = {
"name": "Ravi",
"age": 20
}
print([Link]("name"))

Output

Ravi

Explanation: The method returns the value associated with the key "name".

6. pop() Method (Additional Method)

The pop() method removes the specified key and returns its value.

Syntax

dictionary_name.pop(key)

Example

student = {
"name": "Ravi",
"age": 20
}
[Link]("age")

print(student)

Output

{'name': 'Ravi'}

Purpose

• Removes unwanted elements

• Useful for deletion operations

7. clear() Method (Additional Method)

The clear() method removes all elements from the dictionary.

Syntax

dictionary_name.clear()

Example

student = {
"name": "Ravi",
"age": 20
}

[Link]()

print(student)

Output

{}

Purpose

• Deletes all dictionary contents

• Creates an empty dictionary

[Link] Accessing and Modifying key:value Pairs in Dictionaries.


A dictionary in Python is a collection of key:value pairs, where each key is unique and is used to access its corresponding
value. Dictionaries are mutable, which means their data can be modified after creation.

Accessing Key:Value Pairs

Accessing means retrieving the value associated with a specific key in a dictionary.

Syntax

dictionary_name[key]

Example

student = {'name': 'John', 'age': 20, 'city': 'New York'} print(student['name']) print(student['age'])

Output:

John 20

Explanation

• 'name' and 'age' are keys

• The values are accessed by placing the key inside square brackets

• If the key does not exist, it results in a KeyError

Using get() Method

The get() method is used to access values without causing an error if the key is missing.

Syntax

[Link](key, default_value)

Example

print([Link]('city')) print([Link]('marks', 'Not Found'))

Output:

New York Not Found

Modifying Key:Value Pairs

Modifying means changing the value of an existing key or adding a new key:value pair.

Syntax

dictionary_name[key] = value

1. Updating Existing Value

Example

student['age'] = 25 print(student)

Output:

{'name': 'John', 'age': 25, 'city': 'New York'}

Explanation : The value of 'age' is updated from 20 to 25

2. Adding New Key:Value Pair

Example

student['course'] = 'BCA' print(student)

Output:
{'name': 'John', 'age': 25, 'city': 'New York', 'course': 'BCA'}

Explanation

• Since 'course' key did not exist, it is added

3. Using update() Method

The update() method is used to add or modify multiple key:value pairs at once.

Syntax

[Link](other_dictionary)

Example

[Link]({'age': 30, 'country': 'USA'}) print(student)

Output:

{'name': 'John', 'age': 30, 'city': 'New York', 'course': 'BCA', 'country': 'USA'}

Important Points

• Keys must be unique

• Dictionaries are mutable

• Accessing a missing key using [] gives an error

• get() is safer for accessing values

• Values can be changed, added, or removed easily

Accessing and modifying key:value pairs are fundamental operations in dictionaries. Using indexing, get(), and update()
methods, we can efficiently retrieve and update data. This makes dictionaries very useful for storing and managing structured
data

[Link] example ,explain how to traverse dictionary using key:value pair.

A dictionary is a collection of key:value pairs enclosed within curly braces { }.


Traversing a dictionary means accessing each key and its corresponding value one by one.

dictionary traversal is commonly performed using:

• items() method

• for loop

The items() method returns both keys and values together in tuple form, which makes traversal easy and efficient.

Traversing means visiting every element of the dictionary one after another.

In dictionaries:

• Keys are used to identify values

• Traversal helps in processing all key:value pairs

Traversing using key:value Pair

The most common method of traversing a dictionary is by using:

• items() method

• for loop

The items() method returns:

(key, value)

pairs from the dictionary.


Syntax

for key, value in dictionary_name.items():


statements

Where:

• key → stores dictionary key

• value → stores corresponding value

• items() → returns all key:value pairs

Example 1: Traversing Student Dictionary

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

for key, value in [Link]():


print(key, ":", value)

Output

name : Ravi
age : 20
course : BCA

Explanation

• [Link]() returns all key:value pairs

• The for loop takes:

o key into variable key

o value into variable value

• Each pair is printed one by one

Example 2: Traversing Employee Dictionary

employee = {
"id": 101,
"name": "Anil",
"salary": 25000
}

for key, value in [Link]():


print(key, "=", value)

Output

id = 101
name = Anil
salary = 25000

Explanation: The loop traverses every key:value pair in the dictionary and prints them.

Traversing only Keys

The document also explains that the keys() method returns all keys of a dictionary.

Syntax
for key in dictionary_name.keys():
print(key)

Example

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

for key in [Link]():


print(key)

Output

name
age
course

Traversing only Values

The document also includes the values() method, which returns all dictionary values.

Syntax

for value in dictionary_name.values():


print(value)

Example

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

for value in [Link]():


print(value)

Output

Ravi
20
BCA

Advantages of Traversing Dictionary using key:value Pair

1. Accesses both keys and values together

2. Makes dictionary processing easy

3. Useful for displaying complete records

4. Reduces complexity in programs

5. Efficient for large dictionaries

[Link] Populating Dictionaries with key: value Pairs.

A dictionary in Python is a collection of key:value pairs enclosed within curly braces { }.


Populating a dictionary means adding elements (key:value pairs) into the dictionary.

dictionaries can be populated:

• during dictionary creation


• dynamically using assignment operator

• using the update() method

• using loops and user input

Populating dictionaries is very important because dictionaries are mutable and allow dynamic insertion of data.

In a dictionary:

• Key acts as an identifier

• Value stores the corresponding data

Syntax of Dictionary

dictionary_name = {
key1:value1,
key2:value2
}

1. Populating Dictionary during Creation

The simplest way is to add key:value pairs while creating the dictionary.

Example

student = {
"name": "Ravi",
"age": 20,
"course": "BCA"
}

print(student)

Output

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}

Explanation

• "name", "age", and "course" are keys

• "Ravi", 20, and "BCA" are values

The dictionary is populated at the time of creation itself.

2. Populating Dictionary using Assignment Operator

Dictionary elements can be added dynamically using keys and assignment operator.

Syntax

dictionary_name[key] = value

Example

student = {}

student["name"] = "Ravi"
student["age"] = 20
student["course"] = "BCA"

print(student)

Output

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}


Explanation

• An empty dictionary is created first

• New key:value pairs are added one by one

• If the key does not exist, Python creates it automatically

3. Populating Dictionary using update() Method

The document explains the use of update() method for populating dictionaries.

The update() method inserts new key:value pairs into the dictionary.

Syntax

dictionary_name.update({key:value})

Example

countries = {}

[Link]({"Asia":"India"})
[Link]({"Europe":"Germany"})
[Link]({"Africa":"Sudan"})
print(countries)

Output

{'Asia': 'India', 'Europe': 'Germany', 'Africa': 'Sudan'}

Explanation

• update() adds new key:value pairs

• Each call inserts one new element into the dictionary

4. Populating Dictionary using User Input

The document also demonstrates populating dictionaries dynamically using loops and user input.

Example

build_dictionary = {}

for i in range(0, 2):

dic_key = input("Enter key: ")


dic_val = input("Enter value: ")

build_dictionary.update({dic_key: dic_val})

print(build_dictionary)

Sample Output

Enter key: name


Enter value: Ravi

Enter key: course


Enter value: BCA

{'name': 'Ravi', 'course': 'BCA'}

Explanation

• User enters keys and values


• update() method inserts them into the dictionary

• Loop repeats until required elements are added

5. Populating Dictionary using dict() Function

The dict() function can also create populated dictionaries.

Example using Keyword Arguments

student = dict(name="Ravi", age=20, course="BCA")

print(student)

Output

{'name': 'Ravi', 'age': 20, 'course': 'BCA'}

Example using Iterable

student = dict([("name","Ravi"), ("age",20)])

print(student)

Output

{'name': 'Ravi', 'age': 20}

Modifying Existing Values while Populating

If a key already exists, the new value replaces the old value.

Example

student = {
"name": "Ravi",
"age": 20
}

student["age"] = 21

print(student)

Output

{'name': 'Ravi', 'age': 21}

Advantages of Populating Dictionaries

1. Allows dynamic data storage

2. Easy insertion of elements

3. Fast access using keys

4. Useful for real-time applications

5. Supports organized data storage

[Link] is Tuple? Explain the different ways to create tuple in Python.

A tuple is one of the built-in data types in Python used to store multiple values in a single [Link] is an ordered
collection of elements enclosed within parentheses ( ). Tuples are similar to lists, but tuples are immutable, meaning their
elements cannot be modified after creation.

Tuples can contain:

• integers

• strings
• floating point values

• mixed datatypes

tuples support:

• indexing

• slicing

• packing and unpacking operations

Features of Tuple

1. Tuples are ordered collections

2. Tuples are immutable

3. Tuples allow duplicate values

4. Tuples support indexing and slicing

5. Tuples can store mixed datatypes

Syntax of Tuple

tuple_name = (element1, element2, element3)

Example of Tuple

student = ("Ravi", 20, "BCA")

print(student)

Output

('Ravi', 20, 'BCA')

Different Ways to Create Tuple in Python

tuples can be created in several ways:

1. Creating Empty Tuple

2. Creating Tuple with Multiple Elements

3. Creating Tuple without Parentheses

4. Creating Single Element Tuple

5. Creating Tuple using tuple() Function

6. Creating Nested Tuple

7. Creating Tuple using User Input

1. Creating Empty Tuple

An empty tuple is a tuple with no elements.

Syntax

tuple_name = ()

Example

empty_tuple = ()

print(empty_tuple)

Output
()

Explanation: The tuple contains no elements.

2. Creating Tuple with Multiple Elements

A tuple can be created by placing elements inside parentheses separated by commas.

Example

numbers = (10, 20, 30, 40)

print(numbers)

Output

(10, 20, 30, 40)

Example with Mixed Datatypes

mixed_tuple = (101, "Python", 98.5, True)

print(mixed_tuple)

Output

(101, 'Python', 98.5, True)

Explanation

Tuple elements can belong to different datatypes.

3. Creating Tuple without Parentheses

The document explains that parentheses are optional while creating tuples.
If elements are separated by commas, Python automatically treats them as tuples.

Example

colors = "red", "green", "blue"

print(colors)

Output

('red', 'green', 'blue')

Explanation

Even without parentheses, Python creates a tuple.

4. Creating Single Element Tuple

For a single element tuple, a comma must be placed after the element.
Without comma, Python treats it as a normal value.

Syntax

tuple_name = (element,)

Example

single_tuple = (10,)

print(single_tuple)
print(type(single_tuple))

Output
(10,)
<class 'tuple'>

Example without Comma

value = (10)

print(type(value))

Output

<class 'int'>

Explanation

Without comma, Python considers it an integer.

5. Creating Tuple using tuple() Function

The document also includes creation of tuples using the built-in tuple() function.

Syntax

tuple(iterable)

Example using List

numbers = tuple([1, 2, 3, 4])

print(numbers)

Output

(1, 2, 3, 4)

Example using String

letters = tuple("Python")

print(letters)

Output

('P', 'y', 't', 'h', 'o', 'n')

Explanation: The string is converted into a tuple of characters.

6. Creating Nested Tuple

A nested tuple is a tuple that contains another tuple inside it.

Example

nested_tuple = ((1, 2), (3, 4), (5, 6))

print(nested_tuple)

Output

((1, 2), (3, 4), (5, 6))

Explanation: Each element of the main tuple is itself another tuple.

7. Creating Tuple using User Input

Tuples can also be created dynamically using user input.

Example
numbers = []

for i in range(3):
value = int(input("Enter number: "))
[Link](value)

result = tuple(numbers)

print(result)

Explanation

• User enters values

• Values are first stored in a list

• tuple() function converts the list into a tuple

Accessing Tuple Elements

Tuple elements are accessed using indexing.

Example

colors = ("red", "green", "blue")

print(colors[0])
print(colors[1])

Output

red
green

Immutability of Tuple

According to the document, tuples are immutable, meaning their values cannot be changed after creation.

Example

numbers = (10, 20, 30)

# numbers[1] = 50

Explanation

Python generates an error because tuples do not support item assignment.

Advantages of Tuple

1. Faster than lists

2. Safe data storage due to immutability

3. Supports indexing and slicing

4. Consumes less memory

5. Useful for fixed data

[Link] a note on Indexing and Slicing on Tuple .

A tuple is an ordered and immutable collection of elements enclosed within parentheses ( ).


Since tuples are ordered collections, each element has a specific position number called an index.

In Python, tuple elements can be accessed using:

1. Indexing
2. Slicing

These operations help in retrieving individual elements or extracting parts of a tuple easily.

1. Indexing on Tuple

Indexing is used to access individual elements of a tuple using their position number.

Python follows 0-based indexing, which means:

• First element → index 0

• Second element → index 1

• Third element → index 2

Python also supports negative indexing, where counting starts from the end.

• Last element → -1

• Second last element → -2

Syntax of Indexing

tuple_name[index]

Where:

• tuple_name → Name of the tuple

• index → Position number of the element

Example of Positive Indexing

colors = ("red", "green", "blue", "yellow")

print(colors[0])
print(colors[1])
print(colors[2])

Output

red
green
blue

Explanation

• colors[0] returns the first element "red"

• colors[1] returns the second element "green"

• colors[2] returns the third element "blue"

Negative Indexing on Tuple

Negative indexing is used to access elements from the end of the tuple.

Example

numbers = (10, 20, 30, 40, 50)

print(numbers[-1])
print(numbers[-2])
print(numbers[-3])

Output
50
40
30

Explanation

• -1 refers to the last element

• -2 refers to the second last element

• -3 refers to the third last element

Tuples are immutable, so elements cannot be modified using indexing.

Example

numbers = (10, 20, 30)

# numbers[1] = 50

Explanation: Python generates an error because tuples do not support item assignment.

2. Slicing on Tuple

Slicing is used to extract a portion of a tuple.


It creates a new tuple from selected elements of the original tuple.

Syntax of Tuple Slicing

tuple_name[start:stop]

Where:

• start → Starting index (included)

• stop → Ending index (excluded)

Example 1: Basic Slicing

numbers = (10, 20, 30, 40, 50)

print(numbers[1:4])

Output

(20, 30, 40)

Explanation

Elements from index 1 to 3 are extracted.


The stop index 4 is excluded.

Example 2: Slicing from Beginning

numbers = (10, 20, 30, 40, 50)

print(numbers[:3])

Output

(10, 20, 30)

Explanation

• Start index is not specified

• Python automatically starts from index 0


Example 3: Slicing till End

numbers = (10, 20, 30, 40, 50)

print(numbers[2:])

Output

(30, 40, 50)

Explanation

• Slicing starts from index 2

• Continues till the end of the tuple

Slicing with Step Value

Python allows slicing with a step value.


The step value determines how many positions to skip.

Syntax

tuple_name[start:stop:step]

Example

numbers = (1, 2, 3, 4, 5, 6, 7, 8)

print(numbers[0:8:2])

Output

(1, 3, 5, 7)

Explanation: The step value 2 selects every alternate element.

Slicing using Negative Indexing

Negative indexes can also be used in slicing.

Example

numbers = (10, 20, 30, 40, 50)

print(numbers[-4:-1])

Output

(20, 30, 40)

Reversing a Tuple using Slicing

A tuple can be reversed using slicing with a negative step value.

Example

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

print(numbers[::-1])

Output

(5, 4, 3, 2, 1)

[Link] the different built-in functions and methods in tuple. Explain with example.
A tuple is an ordered and immutable collection of elements enclosed within parentheses ( ).
Since tuples are immutable, only a few methods are available for tuples compared to lists. However, Python provides several
built-in functions that can be used on tuples.

Built-in functions and methods help in:

• accessing tuple data

• performing calculations

• counting elements

• searching values

The important built-in functions and methods used with tuples are:

Built-in Functions

1. len()

2. max()

3. min()

4. sum()

5. tuple()

6. sorted()

Tuple Methods

1. count()

2. index()

Built-in Functions on Tuple

1. len() Function

The len() function is used to find the number of elements present in a tuple.

Syntax

len(tuple_name)

Example

numbers = (10, 20, 30, 40)

print(len(numbers))

Output

Explanation: The tuple contains four elements, so the function returns 4.

2. max() Function

The max() function returns the largest element in the tuple.

Syntax

max(tuple_name)

Example

numbers = (25, 10, 45, 5, 30)

print(max(numbers))
Output

45

Explanation: Among all elements, 45 is the largest value.

3. min() Function

The min() function returns the smallest element in the tuple.

Syntax

min(tuple_name)

Example

numbers = (25, 10, 45, 5, 30)

print(min(numbers))

Output

Explanation: The function returns the minimum element from the tuple.

4. sum() Function

The sum() function calculates the total sum of numeric elements in the tuple.

Syntax

sum(tuple_name)

Example

numbers = (10, 20, 30, 40)

print(sum(numbers))

Output

100

Explanation

The function adds all elements:


10 + 20 + 30 + 40 = 100

5. tuple() Function

The tuple() function is used to create a tuple from another iterable object.

Syntax

tuple(iterable)

Example

letters = tuple("Python")

print(letters)

Output

('P', 'y', 't', 'h', 'o', 'n')

Explanation: The string "Python" is converted into a tuple of characters.

6. sorted() Function
The sorted() function sorts tuple elements and returns them as a list.

Syntax

sorted(tuple_name)

Example

numbers = (40, 10, 30, 20)

print(sorted(numbers))

Output

[10, 20, 30, 40]

Explanation: The tuple elements are arranged in ascending order and returned as a list.

Tuple Methods

Tuples provide only two built-in methods because tuples are immutable.

1. count() Method

The count() method returns the number of times a specified element occurs in the tuple.

Syntax

tuple_name.count(element)

Example

numbers = (10, 20, 10, 30, 10)

print([Link](10))

Output

Explanation:The element 10 appears three times in the tuple.

2. index() Method

The index() method returns the index position of the first occurrence of the specified element.

Syntax

tuple_name.index(element)

Example

numbers = (10, 20, 30, 40)

print([Link](30))

Output

Explanation: The element 30 is located at index position 2.

[Link] example, explain the Basic operations performed on Tuple.

A tuple is an ordered and immutable collection of elements enclosed within parentheses ( ).


Tuples support various operations similar to lists. These operations are used to access, combine, repeat, search, and process
tuple elements.

Since tuples are immutable, their elements cannot be modified after creation.
However, several operations can still be performed on tuples efficiently.
The important basic operations performed on tuples are:

1. Accessing Elements

2. Indexing

3. Slicing

4. Concatenation

5. Repetition

6. Membership Operations

7. Iteration or Traversal

8. Length Operation

1. Accessing Tuple Elements

Tuple elements are accessed using indexes.

Python supports:

• Positive indexing

• Negative indexing

Syntax

tuple_name[index]

Example

colors = ("red", "green", "blue")

print(colors[0])
print(colors[1])

Output

red
green

Explanation

• colors[0] accesses the first element

• colors[1] accesses the second element

2. Indexing Operation

Indexing is used to access a single element from the tuple.

Python follows:

• Positive indexing from left to right

• Negative indexing from right to left

Example of Negative Indexing

numbers = (10, 20, 30, 40)

print(numbers[-1])
print(numbers[-2])

Output

40
30
Explanation

• -1 refers to last element

• -2 refers to second last element

3. Slicing Operation

Slicing is used to extract a portion of the tuple.

Syntax

tuple_name[start:stop]

Example

numbers = (10, 20, 30, 40, 50)

print(numbers[1:4])

Output

(20, 30, 40)

Explanation

Elements from index 1 to 3 are extracted.


Stop index 4 is excluded.

Slicing with Step Value

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

print(numbers[0:6:2])

Output

(1, 3, 5)

Explanation: The step value 2 selects alternate elements.

4. Concatenation Operation

Concatenation joins two tuples together using the + operator.

Syntax

tuple1 + tuple2

Example

tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)

result = tuple1 + tuple2

print(result)

Output

(1, 2, 3, 4, 5, 6)

Explanation: Both tuples are combined into a single tuple.

5. Repetition Operation

The repetition operator * repeats tuple elements multiple times.

Syntax
tuple_name * n

Example

numbers = (1, 2, 3)

print(numbers * 3)

Output

(1, 2, 3, 1, 2, 3, 1, 2, 3)

Explanation: The tuple is repeated three times.

6. Membership Operation

Membership operators are used to check whether an element exists in the tuple.

Python provides:

• in

• not in

Example using in

numbers = (10, 20, 30, 40)

print(20 in numbers)

Output

True

Example using not in

numbers = (10, 20, 30, 40)

print(50 not in numbers)

Output

True

Explanation

• in checks whether element exists

• not in checks whether element does not exist

7. Traversal or Iteration Operation

Traversal means accessing each element of the tuple one by one using loops.

Syntax

for variable in tuple_name:


statements

Example

colors = ("red", "green", "blue")

for color in colors:


print(color)

Output
red
green
blue

Explanation: The loop traverses every element in the tuple.

8. Length Operation

The len() function returns the total number of elements in the tuple.

Syntax

len(tuple_name)

Example

numbers = (10, 20, 30, 40)

print(len(numbers))

Output

Explanation: The tuple contains four elements.

Important Point about Tuple Operations

Tuples are immutable, so operations like insertion, deletion, and modification are not allowed.

Example

numbers = (10, 20, 30)

# numbers[1] = 50

Explanation: Python gives an error because tuple elements cannot be modified.

[Link] populating Tuple with example.

A tuple is an ordered and immutable collection of elements enclosed within parentheses ( ).


Populating a tuple means adding elements into the tuple at the time of creation.

Unlike lists and dictionaries, tuples are immutable, so elements cannot be added, removed, or modified after the tuple is
created. Therefore, tuples are populated only during creation or by creating a new tuple.

Tuples can contain:

• integers

• strings

• floating point values

• mixed datatypes

Populating a tuple means storing elements inside the tuple.

In Python, tuple elements are inserted:

1. During tuple creation

2. Using the tuple() function

3. Using user input

4. By concatenating tuples

Since tuples are immutable, direct insertion after creation is not allowed.
Syntax of Tuple

tuple_name = (element1, element2, element3)

1. Populating Tuple during Creation

The simplest way to populate a tuple is by providing elements inside parentheses.

Example

student = ("Ravi", 20, "BCA")

print(student)

Output

('Ravi', 20, 'BCA')

Explanation

• "Ravi" → first element

• 20 → second element

• "BCA" → third element

The tuple is populated while it is created.

2. Populating Tuple with Multiple Datatypes

A tuple can store elements of different datatypes.

Example

mixed_tuple = (101, "Python", 98.5, True)

print(mixed_tuple)

Output

(101, 'Python', 98.5, True)

Explanation

The tuple contains:

• Integer

• String

• Float

• Boolean value

3. Populating Tuple using tuple() Function

The built-in tuple() function is used to create and populate tuples from iterable objects.

Syntax

tuple(iterable)

Example using List

numbers = tuple([10, 20, 30, 40])

print(numbers)

Output

(10, 20, 30, 40)


Explanation

The list elements are converted into tuple elements.

Example using String

letters = tuple("Python")

print(letters)

Output

('P', 'y', 't', 'h', 'o', 'n')

Explanation

Each character of the string becomes an element of the tuple.

4. Populating Tuple using User Input

Tuples can also be populated dynamically using user input.

Example

numbers = []

for i in range(3):

value = int(input("Enter number: "))


[Link](value)

result = tuple(numbers)

print(result)

Sample Output

Enter number: 10
Enter number: 20
Enter number: 30

(10, 20, 30)

Explanation

• User enters values one by one

• Values are first stored in a list

• tuple() converts the list into a tuple

5. Populating Tuple using Concatenation

Since tuples are immutable, new elements can be added by concatenating tuples.

Example

tuple1 = (1, 2, 3)

tuple2 = (4, 5)

result = tuple1 + tuple2

print(result)

Output
(1, 2, 3, 4, 5)

Explanation

Two tuples are combined to form a new populated tuple.

6. Populating Nested Tuple

A nested tuple contains another tuple inside it.

Example

nested_tuple = ((1, 2), (3, 4), (5, 6))

print(nested_tuple)

Output

((1, 2), (3, 4), (5, 6))

Explanation

Each element of the main tuple is another tuple.

Important Point about Tuple Population

Tuples are immutable, so elements cannot be inserted directly after creation.

Example

numbers = (10, 20, 30)

# numbers[1] = 50

Explanation

Python generates an error because tuple elements cannot be modified.

Accessing Populated Tuple Elements

Tuple elements can be accessed using indexing.

Example

colors = ("red", "green", "blue")

print(colors[0])
print(colors[1])

Output

red
green

[Link] are set ? Explain with example any five set methods .

A set is one of the built-in data types in Python used to store multiple elements in a single variable.
A set is an unordered collection of unique elements enclosed within curly braces { }.

Sets are mainly used when:

• duplicate values should not be allowed

• mathematical set operations are required

• fast searching is needed

Sets are mutable, which means elements can be added or removed after creation.

Definition of Set
A set is an unordered collection of unique elements enclosed within curly braces { }.

Features of Set

1. Sets are unordered

2. Sets do not allow duplicate elements

3. Sets are mutable

4. Sets can store multiple datatypes

5. Sets do not support indexing and slicing

Syntax of Set

set_name = {element1, element2, element3}

Example of Set

numbers = {10, 20, 30, 40}

print(numbers)

Output

{40, 10, 20, 30}

Explanation: The elements may appear in different order because sets are unordered.

Example Showing Unique Elements

numbers = {10, 20, 10, 30, 20}

print(numbers)

Output

{10, 20, 30}

Explanation: Duplicate values are automatically removed.

Set Methods in Python

Python provides several built-in methods for performing operations on sets.

Important set methods are:

1. add()

2. update()

3. remove()

4. discard()

5. pop()

Additional methods:

• clear()

• union()

• intersection()

1. add() Method

The add() method is used to add a single element to a set.

Syntax
set_name.add(element)

Example

numbers = {10, 20, 30}

[Link](40)

print(numbers)

Output

{40, 10, 20, 30}

Explanation

The element 40 is added to the set.

Purpose of add() Method

• Adds single element to set

• Useful for dynamic insertion of values

2. update() Method

The update() method is used to add multiple elements into a set.

Syntax

set_name.update(iterable)

Example

numbers = {10, 20, 30}

[Link]([40, 50, 60])

print(numbers)

Output

{40, 10, 50, 20, 60, 30}

Explanation

Multiple elements are inserted into the set.

Purpose of update() Method

• Adds multiple elements at once

• Useful for combining data

3. remove() Method

The remove() method deletes a specified element from the set.

Syntax

set_name.remove(element)

Example

numbers = {10, 20, 30, 40}

[Link](20)

print(numbers)
Output

{40, 10, 30}

Explanation

The element 20 is removed from the set.

Important Point

If the element does not exist, remove() generates an error.

Purpose of remove() Method

• Removes specified element

• Useful for deletion operations

4. discard() Method

The discard() method also removes an element from the set.

Syntax

set_name.discard(element)

Example

numbers = {10, 20, 30}

[Link](20)

print(numbers)

Output

{10, 30}

Explanation: The element 20 is removed successfully.

Purpose of discard() Method

• Safely removes elements

• Avoids runtime errors

5. pop() Method

The pop() method removes a random element from the set.

Syntax

set_name.pop()

Example

numbers = {10, 20, 30, 40}


[Link]()
print(numbers)

Sample Output: {20, 30, 40}

Explanation: A random element is removed because sets are unordered.

Purpose of pop() Method

• Removes random element

• Useful in set processing operations

Additional Set Methods


clear() Method

Removes all elements from the set.

Example

numbers = {10, 20, 30}


[Link]()
print(numbers)

Output: set()

union() Method

Combines elements of two sets.

Example

A = {1, 2, 3}
B = {3, 4, 5}
print([Link](B))

Output

{1, 2, 3, 4, 5}

intersection() Method

Returns common elements between sets.

Example

A = {1, 2, 3}
B = {2, 3, 4}

print([Link](B))

Output: {2, 3}

[Link] tuple and set datatype

You might also like