0% found this document useful (0 votes)
6 views16 pages

Data Structures Questions: 1. What Are The Different Types of Data Structures in Python?

rfqf

Uploaded by

sainithin667
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Data Structures Questions: 1. What Are The Different Types of Data Structures in Python?

rfqf

Uploaded by

sainithin667
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Data Structures Questions

1. What are the different types of data structures in python?

1. List

 Description: An ordered, mutable (modifiable) collection that allows duplicate


elements.
 Syntax: my_list = [1, 2, 3]

2. Tuple

 Description: An ordered, immutable (non-modifiable) collection. Useful for read-


only data.
 Syntax: my_tuple = (1, 2, 3)

3. Set

 Description: An unordered collection with no duplicate elements. Ideal for operations


like union, intersection, and difference.
 Syntax: my_set = {1, 2, 3}

4. Dictionary

 Description: A collection of key-value pairs. Allows fast retrieval based on keys.


 Syntax: my_dict = {'key1': 'value1', 'key2': 'value2'}

5. String (str): Represents a sequence of characters, e.g., "Hello", "Python".

2. What is a string? What is the data type to represent string value?

A string in Python is a sequence of characters, such as letters, numbers, symbols, or spaces,


used to represent text data. Strings are immutable, meaning once they are created, they
cannot be changed.

Data Type for Strings

The data type used to represent a string value in Python is str.

Examples

Strings can be created by enclosing characters in:

 Single quotes: 'Hello'


 Double quotes: "Hello"
 Triple quotes (for multi-line strings): '''Hello''' or """Hello"""
Example of a String

name = "Vinay Kumar"

greeting = 'Hello, world!'

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.

Data Type for Lists

The data type used to represent a list in Python is list.

Creating a List

Lists are created by placing items inside square brackets [ ], separated by commas.

Example of a List

# Creating a list of integers


numbers = [1, 2, 3, 4, 5]
# Creating a mixed list with different data types
mixed_list = [10, "apple", 3.14, True]
# Creating a nested list
nested_list = [1, [2, 3], [4, 5]]

4. What is a Tuple? What is the data type? Create one tuple?

A tuple in Python is an ordered, immutable collection of items, meaning once a tuple is


created, its elements cannot be modified, added, or removed. Tuples can contain elements of
various data types, including numbers, strings, lists, and even other tuples.

Data Type for Tuples

The data type used to represent a tuple in Python is tuple.


Creating a Tuple

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

# Creating a tuple with multiple items


fruits = ("apple", "banana", "cherry")
# Creating a mixed tuple with different data types
mixed_tuple = (1, "hello", 3.14, True)
# Creating a single-item tuple (note the comma)
single_item_tuple = ("single",)

5. What is a set? What is the data type? Create one set?

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.

Data Type for Sets

The data type used to represent a set in Python is set.

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

# Creating a set of numbers

my_set = {1, 2, 3, 4, 5}

# Creating a set with different data types

mixed_set = {1, "apple", 3.14, True}

# Creating an empty set (must use set() as {} creates an empty dictionary)

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.

Data Type for Dictionaries

The data type used to represent a dictionary in Python is dict.

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

# Creating a dictionary with string keys and various types of values


person = {
"name": "Alice",
"age": 30,
"city": "New York",
"is_student": False
}

# Creating a dictionary with different data types for keys


mixed_dict = {
1: "one",
"two": 2,
(3, 4): "three and four" # tuples can be used as dictionary keys
}

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]

8. What is indexing and slicing? Differences between both?

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

 Definition: Indexing is the process of accessing a single element from a sequence


using its position (or index).
 Syntax: sequence[index]
 Usage: Accesses one specific item at a time.
 Indexing Range: Uses both positive (forward) and negative (backward) indexing.
o Positive indexing starts from 0 for the first element.
o Negative indexing starts from -1 for the last element.
 Example:

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

print(my_list[0]) # Output: 10

print(my_list[-1]) # Output: 50

Slicing

 Definition: Slicing is the process of accessing a subset of elements from a sequence


by specifying a range.
 Syntax: sequence[start:end:step]
 Usage: Retrieves a range of items, defined by a start and end index, and can also
define a step value (to skip elements).
o start: The index to begin the slice (included).
o end: The index to stop at (excluded).
o step: The interval or "step" between items to include.
 Default Values:
o If start is omitted, it defaults to the beginning of the sequence.
o If end is omitted, it defaults to the end of the sequence.
o If step is omitted, it defaults to 1.
 Example:
my_list = [10, 20, 30, 40, 50]

print(my_list[1:4]) # Output: [20, 30, 40]

print(my_list[:3]) # Output: [10, 20, 30] (from start to index 3)

print(my_list[::2]) # Output: [10, 30, 50] (every second element)

9. What are the IndexError and TypeError errors?

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

 Definition: An IndexError occurs when attempting to access an index that is out of


the range of a sequence, such as a list, tuple, or string.
 Cause: This error happens if you try to access an index that is either negative beyond
the allowed range or greater than the maximum index of the sequence.
 Example:

my_list = [10, 20, 30]


print(my_list[3]) # IndexError: list index out of range

 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

 Definition: A TypeError occurs when an operation or function is applied to an object


of an inappropriate type. This happens when an operation is unsupported for the given
data type.
 Cause: This error can happen in a variety of situations, such as trying to add a string
to an integer, calling a method that doesn’t apply to a given type, or using incorrect
arguments.
 Example:

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.

10. Generate a list [10,12,14,16,18,20] by using range function?


You can generate a list containing the even numbers from 10 to 20 using the range() function
in Python. The range() function allows you to specify a starting value, an ending value, and
an increment (step).
Ex:
# Generating the list using range()
even_numbers = list(range(10, 21, 2))
print(even_numbers)
[10, 12, 14, 16, 18, 20]
11. St = ’python developer’
a. Display as ‘Python developer’
a: capitalize() makes the first character uppercase.

b. Display as ‘Python Developer’


b: title() capitalizes the first letter of each word.

c. Count number of Es in that string.


c: count('e') counts occurrences of 'e'.

d. Find index position of first ’o’ in the above string.


d: index('o') finds the position of the first 'o'.

e. Find index position of second ‘o’ in the above string.


e: index('o', start) finds the position of the second 'o'.

f. Spilt the same string into two elements like ‘python’,’developer’


f: split() breaks the string into a list of words

g. Display string in reverse.


g: [::-1] reverses the string.

h. From the above string, display only ‘on dev’.


h: Indexing is used to extract the substring.

i. From above string remove ‘thon’


i: replace() removes 'thon' from the string.

j. Copy the same string into other new strings like str1,str2 and str3 at a time

j: Copies the original string into three new variables.

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]

my_list.append([5, 6]) # Appending a list


print(my_list) # Output: [1, 2, 3, 4, [5, 6]]
2. extend()

 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]

my_list.extend((6, 7)) # Extending with a tuple


print(my_list) # Output: [1, 2, 3, 4, 5, 6, 7]

13. How to convert a list to string? Give one example?

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

Here’s how to convert a list to a string:

# Example list
my_list = ['Hello', 'world', 'this', 'is', 'Python']

# Converting the list to a string with spaces as separators


result_string = ' '.join(my_list)

print(result_string) # Output: Hello world this is Python


Other Examples

1. Using a different separator:

my_list = ['apple', 'banana', 'cherry']


result_string = ', '.join(my_list)
print(result_string) # Output: apple, banana, cherry
2. Using an empty string as a separator:
my_list = ['H', 'e', 'l', 'l', 'o']
result_string = ''.join(my_list)
print(result_string) # Output: Hello

14. Let’s take two sets se1={1,2,3,4,5} se2={1,2,3,6,7}


1. Perform union between se1 and se2, by using ‘I’ also

2. Perform intersection between se2 and se1, by using ‘&’ also

3. Perform difference between se2 and se1, by using ‘-’ also.

4. What intersection_update?and perform between se1 and se2 and vice


versa.

5. What is difference_update?and perform between se1 and se2 and vice


versa.

6. What is symmetric_difference? Perform between se1 and se2 and vice


versa.
7. What is symmetric_difference_update? perform between se1 and se2 and
vice versa.

 Union:
 Using |: {1, 2, 3, 4, 5, 6, 7}
 Using union(): {1, 2, 3, 4, 5, 6, 7}

 Intersection:

 Using &: {1, 2, 3}


 Using intersection(): {1, 2, 3}

 Difference (se2 - se1):

 Using -: {6, 7}
 Using difference(): {6, 7}

 intersection_update:

 se1 after updating with se2: {1, 2, 3}


 se2 after updating with se1: {1, 2, 3}

 difference_update:

 se1 after updating with se2: {4, 5}


 se2 after updating with se1: {6, 7}

 Symmetric Difference:

 Using symmetric_difference(): {4, 5, 6, 7}


 Using ^: {4, 5, 6, 7}

 symmetric_difference_update:

 se1 after updating with se2: {4, 5, 6, 7}


 se2 after updating with se1: {4, 5, 6, 7}

15. Difference between remove() and discard()?

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}

# Trying to remove an element that doesn't exist raises KeyError


try:
my_set.remove(5) # This will raise KeyError
except KeyError:
print("Element 5 not found in the set.")
2. discard()

 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}

# Trying to discard an element that doesn't exist does nothing


my_set.discard(5) # No error raised
print(my_set) # Output: {1, 3, 4}

16. >>> s1={1,2,3}


>>> s2={1,2,3,4} what is the result of
a. s1<s2

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?

 a. s1 < s2: True

 s1s1s1 is a proper subset of s2s2s2 because all elements of s1s1s1 are in s2s2s2, and
s2s2s2 has additional elements.

 b. s1 <= s2: True

 s1s1s1 is a subset of s2s2s2, including the possibility of being equal.

 c. s1 > s2: False

 s1s1s1 is not a proper superset of s2s2s2 because s2s2s2 has elements that are not in
s1s1s1.

 d. s1 >= s2: False

 s1s1s1 is not a superset of s2s2s2.

 e. s1.isdisjoint(s2): False

 s1s1s1 and s2s2s2 are not disjoint; they share common elements (1, 2, 3).

 f. s1.issubset(s2): True

 This checks if s1s1s1 is a subset of s2s2s2, which it is.

 g. s1.issuperset(s2): False

 s1s1s1 does not contain all elements of s2s2s2.

 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

 s2s2s2 contains all elements of s1s1s1.

 j. s1 != s2: True

 The sets are not equal since they have different elements.

 k. 4 not in s2: False

 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 = {}

# Adding key-value pairs

my_dict['name'] = 'Alice'

my_dict['age'] = 30

my_dict['city'] = 'New York'

my_dict['occupation'] = 'Engineer'

my_dict['hobby'] = 'Painting'

# Display the dictionary

print(my_dict)

Output:
{

'name': 'Alice',

'age': 30,

'city': 'New York',

'occupation': 'Engineer',

'hobby': 'Painting'

18. stuDetails={'Id':100,'Name':'Sai', 'subjects':['SQL Server', 'Oracle', 'Python']}


a. modify the value of name as ‘Durga’

b. add new pair age:25

c. display all keys from the stuDetails dictionary?

d. Display all values from the stuDetails dictionary?

e. Display all subjects which are stored in the stuDetails dictionary?

f. Remove name key from the stuDetails?

g. Create new dictionary from the tuple element? Eg:tup=(1,2,3,4,5)

1. Store value ‘Sai’ for key 1


2. Store value ‘Mahesh’ for key 2
3. Store value True for key 3
4. Store value 3+6j for key 4
5. Store value 1000 for key 5

h. remove all pairs from the above dictionary

Eg:

stuDetails = {

'Id': 100,

'Name': 'Sai',

'subjects': ['SQL Server', 'Oracle', 'Python']

}
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)

# Create a dictionary using the elements of the tuple as keys


new_dict = {
tup[0]: 'Sai', # Key 1
tup[1]: 'Mahesh', # Key 2
tup[2]: True, # Key 3
tup[3]: 3 + 6j, # Key 4 (complex number)
tup[4]: 1000 # Key 5
}

# Display the created dictionary


print("Created Dictionary:", new_dict)
h. # Remove all pairs from the new dictionary
new_dict.clear()

# Display the dictionary after clearing


print("Dictionary after clearing:", new_dict)
# Step 1: Initial dictionary
stuDetails = {
'Id': 100,
'Name': 'Sai',
'subjects': ['SQL Server', 'Oracle', 'Python']
}

# a. Modify the value of 'Name' to 'Durga'


stuDetails['Name'] = 'Durga'

# b. Add a new key-value pair 'age': 25


stuDetails['age'] = 25

# c. Display all keys


all_keys = stuDetails.keys()
print("All Keys:", list(all_keys))

# d. Display all values


all_values = stuDetails.values()
print("All Values:", list(all_values))

# e. Display all subjects


subjects = stuDetails['subjects']
print("Subjects:", subjects)

# f. Remove 'Name' key


del stuDetails['Name']
print("Updated Dictionary after removing 'Name':", stuDetails)

# Step 2: Create a new dictionary from the tuple


tup = (1, 2, 3, 4, 5)
new_dict = {
tup[0]: 'Sai', # Key 1
tup[1]: 'Mahesh', # Key 2
tup[2]: True, # Key 3
tup[3]: 3 + 6j, # Key 4
tup[4]: 1000 # Key 5
}

# Display the created dictionary


print("Created Dictionary:", new_dict)

# h. Remove all pairs from the new dictionary


new_dict.clear()
print("Dictionary after clearing:", new_dict)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy