Data Structures Questions: 1. What Are The Different Types of Data Structures in Python?
Data Structures Questions: 1. What Are The Different Types of Data Structures in Python?
1. List
2. Tuple
3. Set
4. Dictionary
Examples
multi_line_string = """This is a
multi-line string."""
3. What is a List? What is the data type of list? Create one list?
A list in Python is an ordered, mutable (modifiable) collection that can contain items of
different data types, such as numbers, strings, or even other lists. Lists allow duplicate
elements and support various operations, including indexing, slicing, and modifying
elements.
Creating a List
Lists are created by placing items inside square brackets [ ], separated by commas.
Example of a List
Tuples are created by placing items inside parentheses ( ), separated by commas. If creating a
tuple with a single item, you must add a comma after the item to differentiate it from a simple
expression.
Example of a Tuple
A set in Python is an unordered, mutable collection that does not allow duplicate elements.
Sets are typically used when you need to store unique items and perform operations like
union, intersection, and difference efficiently.
Creating a Set
Sets are created by placing elements inside curly braces { }, separated by commas.
Alternatively, you can use the set() function to create a set.
Example of a Set
my_set = {1, 2, 3, 4, 5}
empty_set = set()
6. What is dictionary? What is the data type of it? Create one dictionary?
A dictionary in Python is an unordered, mutable collection of key-value pairs, where each
key is associated with a specific value. Dictionaries are useful when you need to store data
that can be quickly accessed by a unique key.
Creating a Dictionary
Dictionaries are created by placing key-value pairs inside curly braces { }, with each key and
value separated by a colon (:). Key-value pairs are separated by commas.
Example of a Dictionary
7. What are the starting index numbers for both forward and backward
indexing?
In Python, indexing allows access to individual elements of sequences (like lists, tuples, and
strings) using a specific index position. Python supports both forward (positive) indexing
and backward (negative) indexing.
Forward Indexing
Starts at 0: The first element in a sequence has index 0, the second element has index
1, and so on.
Example: For a sequence s = ['a', 'b', 'c', 'd'], the indexes are:
o 'a' → s[0]
o 'b' → s[1]
o 'c' → s[2]
o 'd' → s[3]
Backward (Negative) Indexing
Starts at -1: The last element in a sequence has index -1, the second-to-last element
has index -2, and so on.
Example: For the same sequence s = ['a', 'b', 'c', 'd'], the indexes are:
o 'd' → s[-1]
o 'c' → s[-2]
o 'b' → s[-3]
o 'a' → s[-4]
Indexing and slicing are techniques in Python used to access elements within sequences,
such as strings, lists, and tuples. While both allow you to retrieve data, they serve different
purposes and operate differently.
Indexing
print(my_list[0]) # Output: 10
print(my_list[-1]) # Output: 50
Slicing
IndexError and TypeError are common types of exceptions in Python that occur when
code tries to perform an operation that is not valid for the given data.
1. IndexError
In this example, my_list[3] causes an IndexError because my_list has indices from 0
to 2, so index 3 is out of range.
2. TypeError
result = "hello" + 5 # TypeError: can only concatenate str (not "int") to str
In this example, TypeError occurs because you cannot add (concatenate) a string and an
integer.
j. Copy the same string into other new strings like str1,str2 and str3 at a time
12. What are the differences between append() and extend() in list?
In Python, both append() and extend() are methods used to add elements to a list, but they
operate in different ways and have distinct purposes. Here are the main differences between
the two:
1. append()
Functionality: Adds a single element (which can be of any data type) to the end of
the list.
Usage: If you want to add one item, including another list (which will be added as a
single element), you use append().
Return Value: It does not return a new list; instead, it modifies the original list in
place and returns None.
Example:
# Using append()
my_list = [1, 2, 3]
my_list.append(4) # Appending an integer
print(my_list) # Output: [1, 2, 3, 4]
Functionality: Adds multiple elements from an iterable (such as a list, tuple, or set) to
the end of the list. Each element in the iterable is added individually.
Usage: If you want to concatenate another list or iterable to the current list, you use
extend().
Return Value: It modifies the original list in place and returns None.
Example:
# Using extend()
my_list = [1, 2, 3]
my_list.extend([4, 5]) # Extending with a list
print(my_list) # Output: [1, 2, 3, 4, 5]
To convert a list to a string in Python, you can use the join() method of a string. This method
takes all elements of the list and concatenates them into a single string, with a specified
separator between each element.
Example
# Example list
my_list = ['Hello', 'world', 'this', 'is', 'Python']
Union:
Using |: {1, 2, 3, 4, 5, 6, 7}
Using union(): {1, 2, 3, 4, 5, 6, 7}
Intersection:
Using -: {6, 7}
Using difference(): {6, 7}
intersection_update:
difference_update:
Symmetric Difference:
symmetric_difference_update:
In Python, both remove() and discard() are methods used to delete elements from a set.
However, there are key differences in how they handle the removal of elements:
1. remove()
Functionality: The remove() method removes a specified element from the set.
Behavior on Non-existent Element: If the specified element is not found in the set, it
raises a KeyError.
Usage: Use remove() when you want to ensure that the element exists in the set
before attempting to remove it.
Example:
my_set = {1, 2, 3, 4}
# Remove an element
my_set.remove(2)
print(my_set) # Output: {1, 3, 4}
Functionality: The discard() method also removes a specified element from the set.
Behavior on Non-existent Element: If the specified element is not found in the set, it
does nothing and does not raise an error.
Usage: Use discard() when you want to attempt to remove an element without
worrying about whether it exists in the set.
Example:
my_set = {1, 2, 3, 4}
# Discard an element
my_set.discard(2)
print(my_set) # Output: {1, 3, 4}
b. s1<=s2
c. s1>s2
d. s1>=s2
e. s1.isdisjoint(s2)
f. s1.issubset(s2)
g. s1.issuperset(s2)
h. s2.issubset(s1)
i. s2.issuperset(s1)
j. s1!=s2
k. 4 not in s2?
l. 1 in s2?
s1s1s1 is a proper subset of s2s2s2 because all elements of s1s1s1 are in s2s2s2, and
s2s2s2 has additional elements.
s1s1s1 is not a proper superset of s2s2s2 because s2s2s2 has elements that are not in
s1s1s1.
e. s1.isdisjoint(s2): False
s1s1s1 and s2s2s2 are not disjoint; they share common elements (1, 2, 3).
f. s1.issubset(s2): True
g. s1.issuperset(s2): False
h. s2.issubset(s1): False
s2s2s2 is not a subset of s1s1s1 since it contains elements (like 4) that are not in
s1s1s1.
i. s2.issuperset(s1): True
j. s1 != s2: True
The sets are not equal since they have different elements.
4 is in s2s2s2.
l. 1 in s2: True
1 is in s2s2s2.
17. Create one empty dictionary and add any 5 key:value pairs?
You can create an empty dictionary in Python and then add key-value pairs to it. Here’s how
to do that:
Example
# Create an empty dictionary
my_dict = {}
my_dict['name'] = 'Alice'
my_dict['age'] = 30
my_dict['occupation'] = 'Engineer'
my_dict['hobby'] = 'Painting'
print(my_dict)
Output:
{
'name': 'Alice',
'age': 30,
'occupation': 'Engineer',
'hobby': 'Painting'
Eg:
stuDetails = {
'Id': 100,
'Name': 'Sai',
}
a. stuDetails['Name'] = 'Durga'
b. stuDetails['age'] = 25
c. all_keys = stuDetails.keys()
print("All Keys:", list(all_keys))
d. all_values = stuDetails.values()
print("All Values:", list(all_values))
e. subjects = stuDetails['subjects']
print("Subjects:", subjects)
f. del stuDetails['Name']
g. # Define the tuple
tup = (1, 2, 3, 4, 5)