Which data type is immutable in Python?
Tuples are immutable, while lists, dicts, and sets can be changed after creation.
用 80 道免费 Python 编程面试题练习,每道题都附答案和解析。
Tuples are immutable, while lists, dicts, and sets can be changed after creation.
The string "hello" contains five characters, so len() returns 5.
Python uses == to compare values for equality and = to assign a value.
The ** operator performs exponentiation, so 2 ** 3 means 2 multiplied by itself 3 times: 2 x 2 x 2 = 8. Options 6 and 9 come from multiplication or squaring, so option b is correct.
list.pop() removes and returns the last item by default.
An empty pair of square brackets is list literal syntax, so type([]) returns the list class. Tuples use parentheses, dictionaries use braces with colons, and arrays require a separate module.
The def keyword begins a function definition followed by the function name and parameters. Option function is not a Python keyword, and lambda creates an anonymous expression rather than a named function.
range(3) starts at 0 and stops before 3, producing [0, 1, 2].
int("42") converts the string "42" to the integer 42.
The + operator concatenates two strings into one new string, so "a" + "b" produces "ab". Option a is correct; "a + b" would require inserting a plus sign as literal text, and Python does not raise an error here.
A set stores only unique values and automatically removes duplicates, while lists and tuples keep every item in order and dictionaries store key-value pairs. Therefore option b is correct.
The // operator performs floor division, which divides 5 by 2 to get 2.5 and then rounds down to the nearest whole number 2. The / operator would return 2.5, so option b is correct.
% returns the remainder, and 5 divided by 2 leaves a remainder of 1.
The break keyword exits the current loop immediately and continues with the code after the loop. The continue keyword skips only the current iteration, and exit is not the standard loop-control keyword, so option c is correct.
list.append(item) adds the item to the end of the list.
Zero is treated as falsy in Python, so bool(0) is False.
Python uses try and except blocks to catch and handle exceptions.
The + operator concatenates two lists by joining their elements into one new list, so [1, 2] + [3] becomes [1, 2, 3]. Option b would require append semantics, and option d is a tuple.
Curly braces with key-value pairs separated by colons create a dict.
get() returns the default value when the key is not present.
The class keyword defines a new class, and its body contains methods and attributes. Option object is a built-in base, while def defines functions and new is not a Python keyword.
self is the conventional name for the current instance of the class.
When an instance is created, Python automatically calls __init__ to initialize the new object. The other options are not special method names, so option a is correct.
str.upper() returns a copy of the string in uppercase.
max() returns the largest value in an iterable or among arguments.
sum() adds the items in the iterable, giving 1 + 2 + 3 = 6.
A negative index counts from the end, so x[-1] is the last item.
sorted() returns a new list ordered from smallest to largest.
lambda creates a small anonymous function, such as lambda x: x + 1.
map(str, ...) converts each number to a string, producing ["1", "2"].
Set membership uses hashing and is O(1) on average, while list membership is O(n).
A linear search over a list checks items one by one, so worst case is O(n).
Dictionary lookups use a hash table and are O(1) on average.
Tuples are immutable ordered sequences, so their elements cannot be changed in place after creation. Lists are mutable, but tuples are not, which makes option b correct.
isinstance() checks whether 3 is an instance of int and returns True.
len() returns the number of items in a container or iterable.
The count method counts non-overlapping occurrences of the substring, and the letter l appears at positions 2 and 3 in hello. That gives two matches, so option b is correct.
enumerate() returns an iterator of tuples, each containing an index and the corresponding value from the iterable. zip() pairs separate iterables, and index() finds a position, so option a is correct.
zip() pairs the first item of each iterable, then the second item, and so on, producing tuples. Converting to a list gives [(1, "a"), (2, "b")], which matches option a.
A function that contains the yield keyword is a generator function, and calling it returns a generator iterator that produces values lazily. The return keyword ends a normal function, so option b is correct.
next() returns the first item from the iterator, which is 1.
Division by zero is not a valid arithmetic operation in Python, so 1 / 0 raises ZeroDivisionError. ValueError covers invalid values, and IndexError covers sequence positions, making option b correct.
A list with two elements has valid indexes 0 and 1, so accessing index 5 is out of range and raises IndexError. KeyError is for dictionaries, and ValueError is for invalid values.
The dictionary {"a": 1} has only the key a, so looking up b with square brackets raises KeyError. Using the get method would return None instead of raising an error.
Python compares numeric values across types, and 1 equals 1.0.
not False is True; the other expressions evaluate to False or 0.
The substring "x" appears in "example", so the membership test is True.
A separator string calls join(), such as "-".join(["a", "b"]).
Converting a list with duplicates to a set keeps only unique values.
The // operator performs floor division, meaning it divides and rounds down to the nearest whole number. The / operator returns a float, and % returns a remainder, so option b is correct.
Multiplying a string by an integer repeats it three times.
map() applies the given function to every item in the iterable and returns a map iterator of the results. apply() and each() are not built-in functions in the same way, so option a is correct.
filter() keeps only items for which the lambda returns True, so only 3 remains.
The import keyword loads a module and makes its names available in the current namespace. require and include are used by other languages, and load is not Python syntax, so option b is correct.
A docstring is a string literal placed at the start of a module, function, class, or method to document its purpose. It does not change execution speed, delete variables, or create a class, so option a is correct.
__init__.py is the conventional package marker inside a directory.
global tells Python that the name refers to a module-level variable.
id() returns the identity of an object, often its memory address.
In Python, an empty list is falsy, so bool([]) converts it to False. Non-empty containers such as [0] are truthy, and None is a separate value, so option b is correct.
Variable names can start with an underscore and may not start with a digit or contain spaces.
Tuples, strings, and frozensets cannot be modified after creation, so they are immutable. Lists can be changed with methods like append, which makes option d incorrect; options a, b, and c are correct.
append(), extend(), and insert() add items; remove() deletes an item.
set() with or without an iterable creates a set; {} creates an empty dict.
Dict keys must be hashable, values can be any type, and insertion order is preserved in Python 3.7+.
enumerate(), zip(), and map() return iterator objects that produce their values lazily. print() returns None rather than an iterable, so options a, b, and c are correct.
try, except, finally, and raise are all part of Python exception handling.
The first item of a list is at index 0.
Python strings are immutable, so an operation such as concatenation creates a new string object instead of changing the original. The statement is therefore false, and option b is correct.
None represents the absence of a value and is a valid object.
A while loop checks its condition before each iteration and may run zero times.
Starting with Python 3.7, dictionaries officially preserve the order in which keys were inserted. This behavior was an implementation detail earlier, so the statement is true.
is checks whether two names refer to the same object; == compares values.
Functions that do not return a value implicitly return None.
Python uses the word and for logical AND, while && is used in languages like JavaScript and C. The statement is false, so option b is correct.
Multiplication runs before addition, so the result is 2 + 12 = 14.
A function definition starts with the def keyword, followed by the function name, parentheses, and a colon. Typing def correctly creates a named function, so the answer is def.
list.append(item) adds an item to the end of the list.
The raise keyword manually triggers an exception with an optional message. It is commonly used to signal invalid input or an impossible state, so the correct keyword is raise.
yield pauses the function and produces one value at a time.
The value 3.5 is a floating-point number, and type(3.5) returns the float class. The short class name printed by Python is float, so the answer is float.