0% found this document useful (0 votes)
15 views6 pages

Python Practice Questions and Answers

Uploaded by

dassreeenika
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)
15 views6 pages

Python Practice Questions and Answers

Uploaded by

dassreeenika
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

Python Practice Questions

Multiple Choice Questions (25)

1. What is the output of len([1, [2, 3], 4])?

a) 3 b) 4 c) 5 d) Error

2. Which of the following is a valid way to create a list in Python?

a) list = (1, 2, 3) b) list = {1, 2, 3} c) list = [1, 2, 3] d) list = 1, 2, 3

3. Which method adds an item at the end of a list?

a) add() b) append() c) insert() d) extend()

4. What does 'Python'[1:4] return?

a) yth b) ytho c) ytho d) yth

5. How many times will the loop run?

for i in range(2, 10, 2): print(i)

a) 4 b) 5 c) 3 d) Infinite

6. Which of the following will result in a list of characters of a string?

a) list("hello") b) split("hello") c) str("hello") d) tuple("hello")

7. What does str1 * 2 do in Python when str1 = "abc"?

a) Error b) "abcabc" c) "abc2" d) None

8. Which of the following is the correct syntax for a while loop?

a) while x in range(5) b) while x < 5: c) while (x:5) d) for x < 5

9. What is the output?

x = [1, 2, 3]

x[1:2] = [4, 5]

print(x)
Python Practice Questions

a) [1, 4, 5, 3] b) [1, 4, 5] c) [1, 2, 3, 4, 5] d) Error

10. Which function returns the number of items in a list?

a) size() b) length() c) len() d) count()

11. Which keyword is used to skip an iteration inside a loop?

a) break b) pass c) stop d) continue

12. What is the default start index in range(n)?

a) 0 b) 1 c) n d) Error

13. 'Hello'.find('l') returns:

a) 1 b) 2 c) 3 d) 0

14. What does "abc".upper() return?

a) ABC b) abc c) Abc d) Error

15. How to check if "a" is in the list lst?

a) "a" on lst b) "a" includes lst c) "a" in lst d) [Link]("a")

16. What is the result of "Python".replace('t', 'T')?

a) PyThon b) PythoN c) PyTTon d) Error

17. What is the output of list(range(0, 5))?

a) [1, 2, 3, 4, 5] b) [0, 1, 2, 3, 4] c) [0, 1, 2, 3, 4, 5] d) Error

18. How do you remove an element at index 2?

a) pop(2) b) del list[2] c) remove(2) d) Both a and b

19. Which method returns the index of a specified value?

a) position() b) find() c) index() d) place()


Python Practice Questions

20. "apple,banana".split(',') returns:

a) ["apple banana"] b) ['a','p','p','l','e'] c) ['apple', 'banana'] d) Error

21. What will [::-1] do to a list?

a) Sort it b) Reverse it c) Slice first element d) Error

22. Which of these is not a valid loop construct in Python?

a) for b) do-while c) while d) nested for

23. "abcde"[2:] gives:

a) ab b) cde c) bcd d) Error

24. What will be the output?

a = [1, 2]

b=a

[Link](3)

print(a)

a) [1, 2, 3] b) [1, 2] c) [1, 2, 3, 3] d) Error

25. Which of the following can store different data types?

a) List b) Tuple c) Dictionary d) All of the above

Fill in the Blanks (15)

1. A string is a sequence of __________.

2. The __________ loop is used when the number of iterations is not known.

3. The __________ keyword is used to terminate a loop.


Python Practice Questions

4. The method __________ returns the number of times a value appears in a list.

5. To add an element at a specific position in a list, use the __________ method.

6. Strings in Python are __________, meaning they cannot be changed.

7. The __________ function converts other types into a string.

8. The slice s[::2] skips every __________ element.

9. range(1, 10, 2) generates only __________ numbers.

10. The method __________ returns the lowercase version of a string.

11. "hello" + "world" results in __________.

12. Lists are mutable but __________ are not.

13. The __________ operator is used to check membership in a list.

14. You can combine two lists using the + or __________ method.

15. Loop control can be passed without doing anything using the __________ keyword.

Output-Based Questions (10)

1.

x = [10, 20, 30]

print(x[::-1])

2.
Python Practice Questions

word = "banana"

print([Link]('a'))

3.

for i in range(1, 10, 3):

print(i, end=" ")

4.

s = "Hello"

print(s[-2:])

5.

nums = [1, 2, 3]

[Link]([4])

print(nums)

6.

msg = "welcome"

for i in range(len(msg)):

if i % 2 == 0:

print(msg[i], end="")

7.

s = "abc"

s = [Link]("a", "x")

print(s)

8.

lst = [0] * 3

lst[0] = 1

print(lst)
Python Practice Questions

9.

x = [1, 2, 3]

y = x[:]

[Link](4)

print(x)

10.

for i in range(5):

if i == 3:

continue

print(i, end=",")

Common questions

Powered by AI

The 'continue' statement is crucial in loop control as it skips the current iteration and proceeds to the next, useful for conditions where certain iterations should not execute the subsequent code block. This contrasts with 'break', which terminates the loop entirely, and 'pass', a no-operation statement often used as a placeholder. Understanding these distinctions is vital in flow control manipulations, allowing for flexible iteration management and enhancing code readability and logic clarity .

Loop constructs in Python control the flow by iterating over sequences and executing code blocks multiple times. 'For' loops are often used when the number of iterations is known and involve iterating over sequences like lists or ranges. They simplify code reading and writing for sequence traversal. 'While' loops are used when the number of iterations is unknown and continue until a condition becomes false, making them suitable for indefinite repetition bounded by conditions rather than sequence size. The choice between these loops depends on clarity of iteration requirements and whether sequence or condition dictates the loop bounds .

Lists in Python are mutable, ordered collections that can store diverse data types, making them suitable for tasks requiring dynamic modifications. Tuples are immutable and ordered, useful for fixed collections of items where modifications are not needed, providing potential performance benefits. Dictionaries are mutable, unordered collections of key-value pairs, optimized for fast look-up operations, making them ideal for associative arrays or look-up tables. These differences guide use cases: lists for flexible collections, tuples for fixed datasets, and dictionaries for quick access .

Python's list slicing provides functionality for accessing a portion of the list, using a concise syntax with support for specifying start, stop, and step indices. Compared to other languages like Java, where slicing might require manual iteration over indices, Python’s approach offers simplicity and clarity. Additionally, slicing allows for negative indices for flexible referencing from the end of the list, an advantage over languages with only positive indices. This can lead to clearer and more maintainable code .

Python’s 'range()' function generates immutable sequences of numbers, facilitating iteration by providing an efficient, readable method to specify start, stop, and step increments directly in loops. This contrasts with manual iteration logic, which requires explicit initialization, condition checks, and increments, potentially increasing error propensity and reducing readability. 'Range()' abstracts these details, offering bug-resistant and concise code, particularly in iterative operations .

Using the 'in' membership operator in Python lists checks for existence of an element, which can have performance implications for large lists due to linear search time complexity. Misapplying it can lead to inefficient code, particularly if used repeatedly on large data structures without optimization. These issues can be mitigated by ensuring operations are minimized or using alternative data structures like sets for membership checks, which offer average time complexity of O(1) due to hash-based storage .

In Python, strings are immutable, meaning once a string is created, it cannot be modified. This immutability can lead to increased efficiency in memory usage and performance because Python can optimize string storage. However, it also means any modification operation results in the creation of a new string object, which could impact performance when dealing with many modifications. For programming practices, this necessitates awareness during string manipulation operations to avoid unnecessary creation of string objects .

In Python, the slicing operation [::1] returns a shallow copy of the entire list due to the step's positive direction, maintaining the list's original order. In contrast, [::-1] reverses the list by using a negative step, effectively iterating from the last to the first element. These operations showcase Python's versatile slicing capabilities, supporting both direct and reversed traversals, influencing use in scenarios requiring list copies or reversals without altering the original list structure .

In Python, string operations like concatenation (using '+') create new string objects due to immutability, as they cannot alter existing strings. Case conversion methods such as 'upper()' and 'lower()' similarly produce new strings with altered case. These operations impact immutability by necessitating the allocation of new memory space for the modified string result, highlighting the significance of understanding operation effects on memory usage and execution time, especially in performance-critical applications .

Python's 'append()' method adds a single element to the end of a list, maintaining the original object, while 'extend()' merges another iterable's elements. 'Append()' is advantageous for single element additions, but multiple calls can be inefficient for bulk operations. 'Extend()', on the other hand, is more efficient for appending multiple items, mitigating the need for iterative appends. Limitations include potential large memory reallocations for significant extensions, impacting performance. Effective list management involves optimizing operation choice based on operation frequency and list size .

You might also like