/
NordPixel
/
pycore
Обзор
Документация
Войти
/
NordPixel
/
pycore
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
main
python-backend-interview/interview_questions_draft.txt
2 880 строк
157 KB
Mihail Emelyanov
Edit interview questions list
21 мар 2024, 15:41
21 мар 2024, 15:41
4b47c30
Код
Авторство
О чём код?
3. Типы данных 1. None (неопределенное значение переменной) 2. Логические переменные (Boolean Type) 3. Числа (Numeric Type) 1. int – целое число 2. float – число с плавающей точкой 3. complex – комплексное число 4. Списки (Sequence Type) 1. list – список 2. tuple – кортеж 3. range – диапазон 5. Строки (Text Sequence Type ) 1. str 6. Бинарные списки (Binary Sequence Types) 1. bytes – байты 2. bytearray – массивы байт 3. memoryview – специальные объекты для доступа к внутренним данным объекта через protocol buffer 7. Множества (Set Types) 1. set – множество 2. frozenset – неизменяемое множество 8. Словари (Mapping Types) 1. dict – словарь 4. Магические методы? Так называют специальные методы, обрамленные двумя подчеркиваниями. Магические методы представляют простой способ заставить объекты вести себя аналогично встроенным типам. Это, в частности, позволяет стандартизировать поведение базовых операторов с экземплярами класса. 6. Что такое id или id()? Возвращает идентификатор переданного объекта, уникальный на время его существования. 7. Как получить список всех атрибутов объекта или что такое dir()? В простейшем виде с помощью функции dir(). Для объектов, класс которых не определил __dir__(), функция попытается определить атрибуты по данным __dict__. Возвращаемый список может включать не все атрибуты, особенно в случаях с переопределенным __getattr__(). Функция help() показывает строку документации и справку для ее аргумента Функция dir() возвращает список, содержащий пространство имен в объекте 8. Что быстрее dict, list, set, tuple? Средняя временная сложность поиска в множествах и словарях соответствует O(1), в случае последовательностей O(n). Кортежи – это неизменяемый тип, поэтому они могут давать выигрыш в скорости перед списками. 9. Какая разница между одинарным (_) и двойным (__) подчеркиванием? Почему игнорируются имена-идентификаторы, которые начинаются с символа подчеркивания? В питоне не реализована концепция скрытой переменной (private variable), поэтому принято декларировать скрытые переменные первым символом в виде нижнего подчеркивания. Одинарным подчеркиванием задаются частные переменные, функции, методы и классы. Двойное подчеркивание применяется для искажения имен атрибутов в классе (вызвать такой метод стандартным образом не получится). 10. Как в Python воплощены public, private, protected методы? Этот вопрос напрямую связан с предыдущим. Все компоненты класса Python по умолчанию являются открытыми (public). Для защищенных (protected) методов по соглашению Python добавляется префикс одиночного подчеркивания, для закрытых (private) методов – префикс двойного подчеркивания 11. Что такое MRO? MRO – сокращение от method resolution order. То есть это способ разрешения проблемы множественного наследования классов. Для конструирования линеаризации класса в версиях Python с новым стилем классов используется алгоритм C3 линеаризации. 13. Что такое контекстные менеджеры? Где они применяются? Как создать свой контекстный менеджер? Что такое with в питоне? Данная инструкция обеспечивает исполнение кода очистки после исполнения программы. Например, можно использовать ее для открытия файла, совершить с ним какие-то действия и автоматически закрыть файл после завершения работы. Аналогичным образом можно открывать соединение с базой данных и автоматически его закрывать. Код очистки исполняется даже в случае, когда появляется исключение (exception). Контекстные менеджеры – это конструкции, которые упрощают работу с тем или иным интерфейсом. Например, работу с файлами или базами данных. Создаются они с помощью оператора with. Для создания собственного класса контекстного менеджера используется библиотека contextlib. 14. Что такое декораторы с параметрами? В качестве декоратора можно использовать выражение, значение которого – функция, принимающая и возвращающая функцию. А значит, можно создавать декораторы с параметрами (фабрики декораторов). Подробно с примерами. 15. Чем отличаются и как используются декораторы @classmethod и @staticmethod? Базовые декораторы classmethod, staticmethod используются для методов, определённых внутри классов. В метод класса первым аргументом передаётся класс. Аналогично метод экземпляра в первом аргументе получает сам экземпляр. Статичный метод используется в том случае, когда метод не имеет доступа к тому, что представляет собой класс или объект класса. 16. Что такое дескриптор? Дескриптор – атрибут объекта, чьё поведение при доступе переопределяется методами __get__, __set__ и __delete__. Если определен хотя бы один из этих методов, объект становится дескриптором. 17. Что такое метаклассы в Python? В Python классы являются объектами, поэтому они сами должны чем-то генерироваться. Эти конструкции представляют собой своеобразные «классы классов» и называются метаклассами. Примером встроенного метакласса является type. В основном метаклассы используются для создания API. Подробнее читайте в нашей публикации. 18. Как вы тестируете код? Что такое mock? Что такое Pytest? Для модульного тестирования используется unittest или Pytest. Mock – это специальный модуль (ставший недавно частью стандартной библиотеки) для тестирования без существенной адаптации кода под тесты. 19. Как проводится отладка программ на Python? В Python есть модуль pdb. Он позволяет пошагово провести отладку программы. В версии 3.7 появилась функция breakpoint(), которая также облегчает дебаггинг. 20. Что такое PEP8? Соглашение о том, как писать код на Python. Нередко среда разработки после соответствующей настройки позволяет автоматически поддерживать программный код в соответствии с этими правилами или теми, что приняты в компании. 21. Какие есть программы для проверки стиля кода? Каковы их преимущества и недостатки? Скажем, pylint, pyflakes. Наиболее популярные инструменты мы уже описали и сравнили. 22. В чём состоит отличие процессов от потоков? Модули – это subprocess и threading. Использование нескольких процессов аналогично использованию нескольких независимых программ, обмен данными организован через каналы. Если приложение должно выполнять несколько задач в одно и то же время, используются потоки (threads). В этом случае для ограничения доступа потоков к памяти в Python имеется блокировщик GIL. 23. Что такое AsyncIO? Когда его имеет смысл использовать? В отличие от потоков, в AsyncIO переключение между сопрограммами происходит лишь тогда, когда сопрограмма ожидает завершения внешней операции. AsyncIO подойдет, если приложение большую часть времени тратит на чтение/запись данных, а не их обработку, то есть, например, для работы с веб-сокетами. 24. В чем заключается проблема циклических зависимостей? Как ее решить? Циклические зависимости обычно служат признаком некачественного проектирования системы. Временное решение – перенести импорт во вложенные области видимости. В частности, определения функций. 25. Как реализовать шаблон Singleton на Python? Какие есть альтернативы? Стандартный пример описан в примерах PEP-0318. Менее удобна для тестирования реализация через декоратор, элегантнее вариант через метаклассы. 26. Какие шаблоны проектирования вы еще знаете? Какими пользовались? Фабричный метод, абстрактная фабрика, прототип, компоновщик, итератор. 27. Основные фичи питона? Если питон оказался первым языком в опыте программирования, нужно иметь общее понимание о нем. Какие у него основные признаки: - это интерпретируемый язык - в нем динамическая типизация данных - это объектно-ориентированный язык - он лаконичный и внешне простой - распространяется бесплатно - у него большое сообщество 28. В чем разница между списками (list) и кортежами (tuple)? Основная разница в том, что список может изменяться (mutable), а кортеж не может (immutable). 29. Как в питоне работает трёхместный (тернарный) оператор? В питоне есть такие выражения: [если верно] if [выражение] else [если неверно] То есть, когда выражение верное (True), то исполняется код [если верно]. В остальных случаях исполняется код [если неверно]. Например: 30. Питон чувствителен к регистру? Язык считается чувствительным к регистру в случае, если он различает имена "myname" и "Myname". То есть, если он отслеживает разницу регистра (между верхним и нижним). Посмотрим, как с этим в питоне. 31. Предельно допустимая длина идентификатора в питоне? В питоне идентификатор может быть любой длины. Помимо этого есть несколько правил для присвоения имен: - первым символом может быть нижнее подчеркивание (_), символы A-Z или a-z; - остальная часть имени может состоять из символов A-Z/a-z/_/0-9; - не забываем, что питон чувствителен к регистру; - в качестве имени нельзя использовать ключевые слова (keywords): and, def, False, import, not, True, as, del, finally, in, or, try, assert, elif, for, is, pass, while, break, else, from, lambda, print, with, class, except, global, None, raise, yield, continue, exec, if, nonlocal, return. 32. Как можно преобразовать строку (string) в нижний регистр (lowercase)? Для этого используется метод lower(). Для преобразования в верхний регистр (uppercase) используется метод upper(). Еще есть методы isupper() (все символы в верхнем регистре) и islower() (все символы в нижнем регистре), которые проверяют регистр всех символов имени. Еще есть метод istitle(), который проверяет строку на стиль заголовка (все слова должны начинаться с символа в верхнем регистре) 33. Для чего нужен pass (pass statement) в питоне? Зачем нужны break и continue? Они используются для управления последовательностью операций: break останавливает исполнение цикла и переводит исполнение на следующий блок кода, continue как бы перепрыгивает на следующую итерацию цикла и не прекращает его исполнение. Иногда нужно, чтобы код не давал никакого результата и не показывал ошибку, например, если еще не готово, но нужно иметь синтаксический корректный код. Можно поставить pass. Кроме него есть break (break statement), которое разрывает цикл. Наконец, есть continue (continue statement), которое перешагивает на следующую итерацию. 34. Как получить список из всех ключей словаря (dictionary keys)? На такие вопросы нужно отвечать детально, с примерами. Данная задача выполняется с помощью функции keys() 35. Что такое срез? Срез — это методика, которая позволяет получить часть списка, кортежа или строки. 36. Как пишутся комментарии в питоне? Для этого используется символ #. Все, что написано на строке после него, считается комментарием и игнорируется. Комментарии используются для объяснения цели написанного кода. Многострочных комментариев в прямом смысле слова в питоне нет. 37. Как проверить, что все символы строки относятся к алфавитно-цифровым? Для этого используется метод isalnum(). 38. Как перевести первый символ строки в верхний регистр? Для этого есть метод capitalize() 39. Все знают, что сегодня питон в моде. Но истинное принятие новой технологии подразумевает понимание ее недостатков. Что вы можете сказать по этому поводу? Минусы python? Какие в питоне есть ограничения: - интерпретируемая природа питона снижает скорость исполнения программы - его не выгодно использовать для мобильных устройств и браузеров - будучи языком с динамической типизацией данных, он использует утиную типизацию; в связи с этим появляются ошибки исполнения (runtime errors); - в нем слабо развиты возможности доступа к базам данных; поэтому питон не идеальный вариант для приложений с очень большими базами данных; - низкие требования на входе, то есть свои силы в питоне может попробовать каждый; это иногда снижает качество кода; - у питона индивидуально выраженный стиль. 40. Как в питоне узнать, в какой мы сейчас директории? Как узнать текущую директорию в питоне? Для этого используется функция os.getcwd(). Она импортируется из модуля os 41. Что такое приглашение интерпретатора (interpreter prompt)? Когда мы заходим в интерпретатор питона, то видим следующую строку: >>> 42. Что нужно сделать, чтобы функция возвращала значение? Для этого используется ключевое слово return. 43. Что такое блок? Когда мы пишем предложение (statement), нам нужно завершить первую строку двоеточием, а под ним написать блок кода, который исполняется в рамках этого предложения. Каждая строка блока пишется с одинаковым отступом. 44. Если мы не поставим двоеточие в конце строки для цикла "do-while", он все равно сработает? В питоне такой цикл не реализован. Это вопрос из тех, которые с подвохом, когда упоминают элементы других языков. 45. В каких областях питон имеет преимущество, лучше всего использовать? Лучше всего питон использовать в следующих областях: - веб-приложения - графические интерфейсы пользователя для настольных ПК - научные и арифметические приложения - разработка ПО - разработка программ обучения - приложения для бизнеса - сетевые приложения - игры, 3D-графика 46. Можете назвать десять встроенных функций питона? Функция complex() создает комплексное число Функция eval() исполняет строку.0) — min(2,3) Функция filter() отфильтровывает элементы, для которых заданное условие верно. Функция format() помогает задать формат строки: Функция hash() возвращает хэш-значение объекта: Функция hex() преобразовывает число в шестнадцатеричное число: Функция input() читает ввод и возвращает строку: Функция len() возвращает число, показывающее длину строки: Функция locals() возвращает словарь с локальной таблицей имен Функция open() открывает файл 47. Как конвертировать список в строку? Для этого подойдет метод join() 48. Как убрать из списка дубликат элемента? Для этого можно конвертировать список во множество (set) 49. Можете объяснить жизненный цикл треда? Общими словами, цикл выглядит так: - сначала создается класс, который подменяет метод исполнения класса в треде, и создаем экземпляр (instance) для этого класса; - вызываем start(), который готовит тред к исполнению; - переводим тред в состояние исполнения; - можно вызвать разные методы, например sleep() и join(), которые переводят тред в режим ожидания; - когда режим ожидания или исполнения прекращается, другие ожидающие треды подготавливаются к исполнению; - после завершения исполнения тред останавливается. 50. Что такое словарь (dictionary)? Словарь содержит пары типа "ключ: значение" Расскажите про арифметические операторы //, %, и ** Оператор // выполняет целочисленное деление и возвращает целую часть числа, полученного в результате операции Оператор ** возводит в степень Оператор % возвращает результат деления по модулю, то есть остаток после деления 51. Что вам известно про операторы сравнения в питоне? Данные операторы сравнивают значения между собой. Оператор "меньше" (<): если значение с левой стороны от оператора меньше, он возвращает True: Оператор "больше" (>): если значение с левой стороны от оператора больше, он возвращает True: Оператор "меньше или равно" (<=): если значение с левой стороны от оператора меньше значения с правой стороны или равно ему, он возвращает True: Оператор "больше или равно" (>=): если значение с левой стороны от оператора больше значения с правой стороны или равно ему, он возвращает True: Оператор равенства (==): если значения равны, он возвращает True: Оператор неравенства (!=): если значения не равны, он возвращает True: 51. Что такое операторы присвоения в питоне? Все арифметические операторы можно комбинировать с символом присвоения =, *= 52. Расскажите про логические операторы в питоне. Всего их три: and, or, not. Как логический оператор можно использовать XOR ^ 53. Что такое оператор принадлежности? Это операторы in и not in. Они показывают, является ли одно значение частью другого. 54. Расскажите про операторы тождественности. Операторы is и is not показывают, являются ли два значения идентичными. 55. Что такое битовые операторы? Данные операторы выполняют операции в битовом формате. % ^ >> 54. Что такое строка документации (docstring)? Она вносится первой строкой в блок, определяющий содержание функции, класса или метода. Содержит описание их цели и способа исполнения. Обозначается тремя одинарными или двойными кавычками с каждой стороны. __doc__ 55. Как можно конвертировать строку в число? Если строка содержит только числовые символы, можно использовать функцию int() 56. Как можно принять результат ввода на клавиатуре? Если пользователь что-то вводит с помощью клавиатуры, можно использовать функцию input(). В качестве аргумента можно задать данной функции текст запроса на ввод. Результат ввода всегда является строкой. 57. Что такое рекурсия? Может ли рекурсия создавать сложности? Какие преимущества у рекурсии? Это когда функция вызывает саму себя. При этом она должна иметь базовое условие, чтобы не создать бесконечный цикл Разумеется: ● Приходится чаще вызывать функцию. ● Каждый вызов функции сохраняет переменную состояния в программном стеке, то есть растет потребление памяти, что в итоге может стать причиной переполнения памяти. ● Вызовы функции отнимают время. Рекурсия помогает: ● экономить усилия на выполнение задачи, ● сократить объем кода по сравнению с циклами, ● легче воспринимать код. 58. Что делает функция zip()? Возвращает итератор с кортежами: В данном случае она совмещает элементы двух списков и создает из них кортежи. Работает не только со списками. 59. Как посчитать длину строки (string)? Для этого вызываем функцию len() 60. Расскажите про генераторы списков (list comprehension). Они позволяют создавать списки с помощью одной строки кода 61. Как можно получить все значения из словаря? Для этого используется метод values() 62. Как можно переключить регистр строки? Можно использовать метод swapcase(), предусмотренный для класса str 63. Для чего используется bytes()? Это встроенная функция питона, которая возвращает неизменяемый байтовый объект 64. Что такое оператор контроля последовательности (control flow statement)? Обычно программа в питоне начинает исполнение с первой строки. После нее программа однократно исполняет каждое предложение. Когда будет исполнено последнее предложение, программа прекращается. Также контроль последовательности помогает усложнить обычный порядок исполнения программы. 65. Как работать с числами, которые не входят в десятичную систему счисления? В питоне можно вводить бинарные, восьмеричные и шестнадцатеричные числа. Бинарные. Это числа, составленные из 0 и 1. Для ввода в бинарном формате, используется префикс 0b или 0B: Число можно преобразовать в бинарный формат с помощью функции bin(): Восьмеричные числа могут состоять из цифр от 0 до 7, также используется префикс 0o или 0O: Шестнадцатеричные числа могут состоять из цифр от 0 до 15, также используется префикс 0x или 0X: 66. Чем Python отличается от Java? Сравнение Python с другим языком Если сравнивать Python и Java: - Java быстрее - Python использует отступы, а Java нужны скобки - в Python динамическая типизация, а в Java — статическая - Python — простой и лаконичный, а Java — многословный язык - Python — интерпретируемый язык - Java не зависит от используемой платформы - в Java есть интерфейс JDBC, который улучшает доступ к базам данных 67. Как выйти из бесконечного цикла? Можно нажать комбинацию клавиш Ctrl+C, которая прерывает исполнение. 68. Как исполняется код в питоне? Файлы питона сначала компилируются в байткод, который затем исполняется 69. Расскажите, какой в питоне механизм передачи параметров. В питоне используется передача параметров по ссылке. Если изменить параметр внутри функции, то это отразится на выводе функции. Однако, если использовать в качестве параметров литералы (строки, числа, кортежы), то они передаются по значению (потому что они не изменяемые). 70. Чем файл .pyc отличается от .py? Оба файла содержат байткод, но .pyc является компилированной версией файла питона. Его байткод не зависит от платформы, поэтому он исполняется на всех платформах, которые поддерживают формат .pyc. 71. Что делает питон объектно-ориентированным? ООП Он следует парадигме объектно-ориентированного программирования, которая построена вокруг классов (classes) и их экземпляров (instances). Это позволяет реализовать следующие функции: - сокрытие внутренней структуры данных - абстракция - наследование - полиморфизм (способность выбирать правильный метод в зависимости от типа данных) - ограничение доступа к данным 72. Когда в блоке try-except исполняется элемент else? В блоке if-else элемент else исполняется в случае, если условие в операторе if (if statement) является неверным (False). А вот в блоке try-except элемент else исполняется только в случае, если элемент try не выдает исключение. 73. Что такое переменная PYTHONPATH? PYTHONPATH — эта переменная сообщает интерпретатору путь до файлов модуля, импортированных в программу. Поэтому она должна включать в себя директорию с библиотекой-источником питона и директории с исходным кодом питона. Переменную PYTHONPATH можно назначить самостоятельно, однако обычно ее предустанавливает установщик питона. 74. Расскажите про функции join() и split() в Python. Функция join() позволяет соединять символы строки (string), чередуя с указанным символом. Функция split() позволяет разделить строку, чередуя символы с указанным символом. 75. Приведите несколько методов, с помощью которых можно реализовать в питоне функционально ориентированное программирование. Несколько методов могут помочь с итерацией по списку (list). filter() может отфильтровать несколько значений на основе условия. map() применяет функцию к каждому элементу итерируемого объекта. reduce() продолжает уменьшать последовательность (sequence) парами, пока не будет достигнуто единичное значение. 75. Можно ли сказать, что del и remove() — это одно и то же? Что это такое, в целом? del и remove() — это методы для списков, они нужны для удаления элементов del позволяет удалять элементы под конкретным индексом, а remove() позволяет удалять элементы на основе их значения. 76. Какие различия есть между методами для списков append() и extend()? Метод append() добавляет элемент к концу списка, а метод extend() добавляет к концу списка переданный ему итерируемый объект (iterable). 77. Какие есть режимы обработки файлов в Python? Предусмотрены следующие режимы: ● только чтение – ‘r’ ● только запись – ‘w’ ● чтение-запись – ‘rw’ ● добавление в конце – ‘a’ Можно открыть текстовый файл с опцией ‘t’. Поэтому, чтобы открыть текстовый файл для чтения, можно использовать режим ‘rt’. Точно так же для бинарных файлов используется ‘b’. 78. Что делает функция map()? Функция map() возвращает итератор, который применяет функцию, переданную ей в первом аргументе, ко всем элементам итерируемого объекта (iterable), переданного ей во втором аргументе. Можно показать пример? 79. Расскажите про try, raise и finally. Это ключевые слова (keywords) для обработки исключений (exception handling). Потенциально рискованный код помещается в блок try, оператор raise (raise statement) используется для прямого вызова ошибки, а в блоке finally находится код, который исполняется в любом случае. 80. Что случится, если не обработать ошибку в блоке except? Если этого не сделать, программа завершится. Затем она отправит трассу исполнения на sys.stderr. 81. Как можно преобразовать целое число (integer) в символ Unicode? Для этого просто нужна встроенная функция chr(x). 82. Если строка (string) начинается с пробела, как его убрать? Такой пробел можно убрать с помощью метода lstrip(). Такой пробел можно убрать с помощью метода lstrip(). В этой строке пробелы стояли как в начале, так и в конце. Функция lstrip() убрала крайний слева пробел из строки. Если мы захотим убрать пробел из хвоста, то воспользуемся функцией rstrip().\ 83. Что за функция enumerate() в Python? Функция enumerate() осуществляет итерацию вдоль последовательности (sequence), извлекает индекс и его значение. 84. В каком случае while уместнее, чем for? В целом, for подойдет во всех случаях, когда применим while, однако есть несколько ситуаций, когда с циклом while проще: ● Простые повторяющиеся циклы ● Когда не нужно осуществлять итерацию вдоль списка элементов (например, записи в базе данных и символы строки. 85. Объясните разницу между полной копией (deep copy) и поверхностной копией (shallow copy). Полное копирование создает новый объект-копию. То есть, если внести изменение в копию объекта, то с первоначальным объектом ничего не случится. В Python для этого используется функция deepcopy() с помощью импорта из модуля copy. Поверхностная копия копирует на новый объект ту ссылку, которая закреплена на первоначальном объекте. Поэтому если внести изменение в копию, то оно распространится на первоначальный объект. Данный функционал реализуется с помощью функции copy(). 86. Можно ли сказать, что массив (array) NumPy лучше списка (list)? Массивы NumPy имеют три преимущества перед списками: ● Они быстрее ● Они потребляют меньше памяти ● С ними удобнее работать 87. Как можно отслеживать разные версии кода? Для этого используется контроль версий (version control). Одним из возможных инструментов контроля является Git. 88. Можно ли осуществить динамическую загрузку модуля в Python? При динамической загрузке модули загружаются только когда они становятся нужны. Такой подход — медленный, но он помогает эффективнее использовать память. В Python для этого можно использовать модуль importlib: 89. Какие методы/функции мы используем для определения типа экземпляра (type of instance) и наследования (inheritance)? Для этого используются type(), isinstance() и issubclass(). 1. type() используется для определени типа объекта. 2. isinstance() принимает два аргумента: значение (value) и тип (type). Если значение относится к соответствующему типу, то возвращается True. Если нет, то возвращается False. 3. issubclass() принимает два класса (classes) в качестве аргументов (arguments). Если второй наследует из первого, то возвращается True. Если нет, то возвращается False. 90. Методы (methods) и конструкторы (constructors) — это одно и то же или нет? Разница между ними очень тонкая, но важная: ● Название конструктора должно соответствовать названию класса, а метод можно называть как угодно. ● Конструктор исполняется при создании объекта, а метод исполняется при его вызове. ● Конструктор исполняется один раз для каждого объекта, а метод можно вызывать по одному объекту неограниченно. ● Конструкторы используются для определения (define) и инициализации не статических переменных. Методы используются для осуществления операций в рамках бизнес-логики. 91. Что понимается под модулем в питоне? Модуль — это скрипт, в котором определяются операторы импорта (import statements), функции (functions), классы (classes) и переменные (variables). Файлы ZIP и DLL тоже могут быть модулями. Название модуля хранится в глобальной переменной (global variable) в виде строки (string). 92. Какие в питоне есть модули для работы с файлами? Питон предлагает следующие библиотеки и модули для обработки текстов и двоичных файлов: os os.path shutil 93. Можете коротко объяснить, как используются модули sqlite3, ctypes, pickle, traceback и itertools. ● sqlite3 помогает обрабатывать базы данных, например SQLite ● ctypes позволяет создавать в питоне типы данных из Си и обрабатывать их ● pickle позволяет переносить любые структуры данных во внешние файлы ● traceback позволяет извлекать, форматировать и выводить на печать трассы вызовов (stack traces) ● itertools помогает работать с перестановками (permutations), комбинациями (combinations) и другими итерируемыми объектами (iterables). 94. Расскажите про наследование (inheritance) в Python. Когда один класс наследует из другого, его называют дочерним/производным/подклассом (child/derived/sub class), который наследует из родительского/базового/супер класса (parent/base/super class). Он наследует/получает все атрибуты и методы. Наследование позволяет повторно использовать код и облегчает создание и дальнейшую работу приложений (applications). В Python поддерживаются следующие виды наследования: ● Единичное наследование (Single Inheritance) — класс наследует из одного базового класса. ● Множественное наследование (Multiple Inheritance) — класс наследует из двух или нескольких базовых классов. ● Многоуровневое наследование (Multilevel Inheritance) — класс наследует из базового класса, который, в свою очередь, наследует из другого базового класса. ● Иерархическое наследование (Hierarchical Inheritance) — два класса или несколько классов наследуют из одного базового класса (single base class). ● Гибридное наследование (Hybrid Inheritance) — сочетание двух или нескольких видов наследования. 95. Объясните, как в Python осуществляется управление памятью. В Python объекты и структуры данных (data structures) находятся в закрытой динамически выделяемой области (private heap), которая управляется менеджером памяти Python. Он делегирует часть работы программам распределения ресурсов (allocators), закрепленным за конкретными объектами, и одновременно с этим следит, чтобы они не выходили за пределы динамически выделяемой области. По факту данной областью управляет интерпретатор (interpreter). Пользователь никак не контролирует данный процесс, даже когда манипулирует ссылками объектов на блоки памяти внутри динамической области. Менеджер памяти Python распределяет пространство динамической области среди объектов и другие внутренние буферы по требованию. 96. Как можно сделать скрипт Python, исполняемый в Unix? Для этого должны выполняться два условия: ● Файл скрипта должен быть в исполняемом режиме. ● Первая строка должен начинаться с решетки (хэша, hash(#)), например: #!/usr/local/bin/python 97. Что такое временная подмена (Monkey Patching)? Она модифицирует класс или модуль во время выполнения (at runtime), то есть представляет собой динамическую модификацию (dynamic modification). Почему def foo(bar=[]): плохо? Приведите пример плохого случая. Как исправить? Почему нельзя сделать пустой список аргументом по умолчанию? Функция создается однажды при загрузке модуля. Именованные параметры и их дефолтные значения тоже создаются один раз и хранятся в одном из полей объекта-функции. В нашем примере bar равен пустому списку. Список – изменяемая коллекция, поэтому значение bar может изменяться от вызова к вызову. Пример: def foo(bar=[]): bar.append(1) return bar foo() [1] foo() [1, 1] foo() [1, 1, 1] Хорошим тоном считается указывать параметру пустое неизменяемое значение, например 0, None, '', False. В теле функции проверять на заполненность и создавать новую коллекцию: def foo(bar=None): if bar is None: bar = [] bar.append(1) return bar foo() [1] foo() [1] foo() [1] Q6. How is memory managed in Python? Q8. What is Python PATH? Q9. What are Python modules? Q10. What are local variables and global variables in Python? Q1. What is the difference between list and tuples in Python? LIST vs TUPLES LIST TUPLES Lists are mutable i.e they can be edited. Tuples are immutable (tuples are lists which can’t be edited). Lists are slower than tuples. Tuples are faster than list. Syntax: list_1 = [10, ‘Chelsea’, 20] Syntax: tup_1 = (10, ‘Chelsea’ , 20) Q2. What are the key features of Python? Python is an interpreted language. That means that, unlike languages like C and its variants, Python does not need to be compiled before it is run. Other interpreted languages include PHP and Ruby. Python is dynamically typed, this means that you don’t need to state the types of variables when you declare them or anything like that. You can do things like x=111 and then x="I'm a string" without error Python is well suited to object orientated programming in that it allows the definition of classes along with composition and inheritance. Python does not have access specifiers (like C++’s public, private). In Python, functions are first-class objects. This means that they can be assigned to variables, returned from other functions and passed into functions. Classes are also first class objects. Writing Python code is quick but running it is often slower than compiled languages. Fortunately,Python allows the inclusion of C-based extensions so bottlenecks can be optimized away and often are. The numpy package is a good example of this, it’s really quite quick because a lot of the number-crunching it does isn’t actually done by Python Python finds use in many spheres – web applications, automation, scientific modeling, big data applications and many more. It’s also often used as “glue” code to get other languages and components to play nice. Learn more about Big Data and its applications from the Data Engineering Training. Q3. What type of language is Python? Programming or scripting? Ans: Python is capable of scripting, but in general sense, it is considered as a general-purpose programming language. To know more about Scripting, you can refer to the Python Scripting Tutorial. Q7.What are Python namespaces? Ans: A namespace in Python refers to the name which is assigned to each object in Python. The objects are variables and functions. As each object is created, its name along with space(the address of the outer function in which the object is), gets created. The namespaces are maintained in Python like a dictionary where the key is the namespace and value is the address of the object. There 4 types of namespace in Python- Built-in namespace– These namespaces contain all the built-in objects in Python and are available whenever Python is running. Global namespace– These are namespaces for all the objects created at the level of the main program. Enclosing namespaces– These namespaces are at the higher level or outer function. Local namespaces– These namespaces are at the local or inner function. Q8.What are decorators in Python? Ans: Decorators are used to add some design patterns to a function without changing its structure. Decorators generally are defined before the function they are enhancing. To apply a decorator we first define the decorator function. Then we write the function it is applied to and simply add the decorator function above the function it has to be applied to. For this, we use the @ symbol before the decorator. Q10.What are the common built-in data types in Python? Ans: The common built-in data types in Python are- Numbers– They include integers, floating-point numbers, and complex numbers. eg. 1, 7.9,3+4i List– An ordered sequence of items is called a list. The elements of a list may belong to different data types. Eg. [5,’market’,2.4] Tuple– It is also an ordered sequence of elements. Unlike lists , tuples are immutable, which means they can’t be changed. Eg. (3,’tool’,1) String– A sequence of characters is called a string. They are declared within single or double-quotes. Eg. “Sana”, ‘She is going to the market’, etc. Set– Sets are a collection of unique items that are not in order. Eg. {7,6,8} Dictionary– A dictionary stores values in key and value pairs where each value can be accessed through its key. The order of items is not important. Eg. {1:’apple’,2:’mango} Boolean– There are 2 boolean values- True and False. Q11.What is the difference between .py and .pyc files? Ans: The .py files are the Python source code files. While the .pyc files contain the bytecode of the Python files. .pyc files are created when the code is imported from some other source. The interpreter converts the source .py files to .pyc files which helps by saving time. You can get a better understanding with the Data Engineering Course in Washington. Q12.What is slicing in Python? Ans: Slicing is used to access parts of sequences like lists, tuples, and strings. The syntax of slicing is-[start:end:step]. The step can be omitted as well. When we write [start:end] this returns all the elements of the sequence from the start (inclusive) till the end-1 element. If the start or end element is negative i, it means the ith element from the end. The step indicates the jump or how many elements have to be skipped. Eg. if there is a list- [1,2,3,4,5,6,7,8]. Then [-1:2:2] will return elements starting from the last element till the third element by printing every second element.i.e. [8,6,4]. Q13.What are Keywords in Python? Ans: Keywords in Python are reserved words that have special meaning.They are generally used to define type of variables. Keywords cannot be used for variable or function names. There are following 33 keywords in Python- And Or Not If Elif Else For While Break As Def Lambda Pass Return True False Try With Assert Class Continue Del Except Finally From Global Import In Is None Nonlocal Raise Yield Q14.What are Literals in Python and explain about different Literals Ans: A literal in Python source code represents a fixed value for primitive data types. There are 5 types of literals in Python- String literals– A string literal is created by assigning some text enclosed in single or double quotes to a variable. To create multiline literals, assign the multiline text enclosed in triple quotes. Eg.name=”Tanya” A character literal– It is created by assigning a single character enclosed in double quotes. Eg. a=’t’ Numeric literals include numeric values that can be either integer, floating point value, or a complex number. Eg. a=50 Boolean literals– These can be 2 values- either True or False. Literal Collections– These are of 4 types- a) List collections-Eg. a=[1,2,3,’Amit’] b) Tuple literals- Eg. a=(5,6,7,8) c) Dictionary literals- Eg. dict={1: ’apple’, 2: ’mango, 3: ’banana`’} d) Set literals- Eg. {“Tanya”, “Rohit”, “Mohan”} 6. Special literal- Python has 1 special literal None which is used to return a null variable. Q15.How to combine dataframes in pandas? Ans: The dataframes in Python can be combined in the following ways- Concatenating them by stacking the 2 dataframes vertically. Concatenating them by stacking the 2 dataframes horizontally. Combining them on a common column. This is referred to as joining. The concat() function is used to concatenate two dataframes. Its syntax is- pd.concat([dataframe1, dataframe2]). Dataframes are joined together on a common column called a key. When we combine all the rows in dataframe it is union and the join used is outer join. While, when we combine the common rows or intersection, the join used is the inner join. Its syntax is- pd.concat([dataframe1, dataframe2], axis=’axis’, join=’type_of_join) Q16.What are the new features added in Python 3.9.0.0 version? Ans: The new features in Python 3.9.0.0 version are- New Dictionary functions Merge(|) and Update(|=) New String Methods to Remove Prefixes and Suffixes Type Hinting Generics in Standard Collections New Parser based on PEG rather than LL1 New modules like zoneinfo and graphlib Improved Modules like ast, asyncio, etc. Optimizations such as optimized idiom for assignment, signal handling, optimized Python built ins, etc. Deprecated functions and commands such as deprecated parser and symbol modules, deprecated functions, etc. Removal of erroneous methods, functions, etc. Q17. How is memory managed in Python? Ans: Memory is managed in Python in the following ways: Memory management in Python is managed by Python private heap space. All Python objects and data structures are located in a private heap. The programmer does not have access to this private heap. The Python interpreter takes care of this instead. The allocation of heap space for Python objects is done by Python’s memory manager. The core API gives access to some tools for the programmer to code. Python also has an inbuilt garbage collector, which recycles all the unused memory and so that it can be made available to the heap space. Q18. What is namespace in Python? Ans: A namespace is a naming system used to make sure that names are unique to avoid naming conflicts. Q19. What is PythonPATH? Ans: It is an environment variable which is used when a module is imported. Whenever a module is imported, PythonPATH is also looked up to check for the presence of the imported modules in various directories. The interpreter uses it to determine which module to load. Q20. What are Python modules? Name some commonly used built-in modules in Python? Ans: Python modules are files containing Python code. This code can either be functions classes or variables. A Python module is a .py file containing executable code. Q21.What are local variables and global variables in Python? Global Variables: Variables declared outside a function or in global space are called global variables. These variables can be accessed by any function in the program. Local Variables: Any variable declared inside a function is known as a local variable. This variable is present in the local space and not in the global space. Example: 1 2 3 4 5 6 a=2 def add(): b=3 c=a+b print(c) add() Output: 5 When you try to access the local variable outside the function add(), it will throw an error. Q22. Is Python case sensitive? Ans: Yes. Python is a case sensitive language. Q23.What is type conversion in Python? Ans: Type conversion refers to the conversion of one data type into another. int() – converts any data type into integer type float() – converts any data type into float type ord() – converts characters into integer hex() – converts integers to hexadecimal oct() – converts integer to octal tuple() – This function is used to convert to a tuple. set() – This function returns the type after converting to set. list() – This function is used to convert any data type to a list type. dict() – This function is used to convert a tuple of order (key, value) into a dictionary. str() – Used to convert integer into a string. complex(real,imag) – This function converts real numbers to complex(real,imag) number. Q28.What is __init__? Ans: __init__ is a method or constructor in Python. This method is automatically called to allocate memory when a new object/ instance of a class is created. All classes have the __init__ method. Here is an example of how to use it. 1 2 3 4 5 6 7 8 9 10 11 class Employee: def __init__(self, name, age,salary): self.name = name self.age = age self.salary = 20000 E1 = Employee("XYZ", 23, 20000) # E1 is the instance of class Employee. #__init__ allocates memory for E1. print(E1.name) print(E1.age) print(E1.salary) Output: XYZ 23 20000 Q29.What is a lambda function? Ans: An anonymous function is known as a lambda function. This function can have any number of parameters but, can have just one statement. Q31. How does break, continue and pass work? Break Allows loop termination when some condition is met and the control is transferred to the next statement. Continue Allows skipping some part of a loop when some specific condition is met and the control is transferred to the beginning of the loop Pass Used when you need some block of code syntactically, but you want to skip its execution. This is basically a null operation. Nothing happens when this is executed. Q33. How can you randomize the items of a list in place in Python? Ans: Consider the example shown below: 1 2 3 4 from random import shuffle x = ['Keep', 'The', 'Blue', 'Flag', 'Flying', 'High'] shuffle(x) print(x) The output of the following code is as below. ['Flying', 'Keep', 'Blue', 'High', 'The', 'Flag'] Q34. What are Python iterators? Ans: Iterators are objects which can be traversed though or iterated upon. Q35. How can you generate random numbers in Python? Ans: Random module is the standard module that is used to generate a random number. The method is defined as: 1 2 import random random.random The statement random.random() method return the floating-point number that is in the range of [0, 1). The function generates random float numbers. The methods that are used with the random class are the bound methods of the hidden instances. The instances of the Random can be done to show the multi-threading programs that creates a different instance of individual threads. The other random generators that are used in this are: randrange(a, b): it chooses an integer and define the range in-between [a, b). It returns the elements by selecting it randomly from the range that is specified. It doesn’t build a range object. uniform(a, b): it chooses a floating point number that is defined in the range of [a,b).Iyt returns the floating point number normalvariate(mean, sdev): it is used for the normal distribution where the mu is a mean and the sdev is a sigma that is used for standard deviation. The Random class that is used and instantiated creates independent multiple random number generators. Q36. What is the difference between range & xrange? Ans: For the most part, xrange and range are the exact same in terms of functionality. They both provide a way to generate a list of integers for you to use, however you please. The only difference is that range returns a Python list object and x range returns an xrange object. This means that xrange doesn’t actually generate a static list at run-time like range does. It creates the values as you need them with a special technique called yielding. This technique is used with a type of object known as generators. That means that if you have a really gigantic range you’d like to generate a list for, say one billion, xrange is the function to use. Data Science Training This is especially true if you have a really memory sensitive system such as a cell phone that you are working with, as range will use as much memory as it can to create your array of integers, which can result in a Memory Error and crash your program. It’s a memory hungry beast. Q37. How do you write comments in Python? Ans: Comments in Python start with a # character. However, alternatively at times, commenting is done using docstrings(strings enclosed within triple quotes). Example: 1 2 3 <span data-mce-type="bookmark" style="display: inline-block; width: 0px; overflow: hidden; line-height: 0;" class="mce_SELRES_end"></span> <pre><span>#Comments in Python start like this print("Comments in Python start with a #") Output: Comments in Python start with a # Q38. What is pickling and unpickling? Ans: Pickle module accepts any Python object and converts it into a string representation and dumps it into a file by using dump function, this process is called pickling. While the process of retrieving original Python objects from the stored string representation is called unpickling. Q39. What are the generators in Python? Ans: Functions that return an iterable set of items are called generators. Q40. How will you capitalize the first letter of string? Ans: In Python, the capitalize() method capitalizes the first letter of a string. If the string already consists of a capital letter at the beginning, then, it returns the original string. Q41. How will you convert a string to all lowercase? Ans: To convert a string to lowercase, lower() function can be used. Example: 1 2 stg='ABCD' print(stg.lower()) Output: abcd Q42. How to comment multiple lines in Python? Ans: Multi-line comments appear in more than one line. All the lines to be commented are to be prefixed by a #. You can also a very good shortcut method to comment multiple lines. All you need to do is hold the ctrl key and left click in every place wherever you want to include a # character and type a # just once. This will comment all the lines where you introduced your cursor. Q44. What is the purpose of ‘is’, ‘not’ and ‘in’ operators? Ans: Operators are special functions. They take one or more values and produce a corresponding result. is: returns true when 2 operands are true (Example: “a” is ‘a’) not: returns the inverse of the boolean value in: checks if some element is present in some sequence Q45. What is the usage of help() and dir() function in Python? Ans: Help() and dir() both functions are accessible from the Python interpreter and used for viewing a consolidated dump of built-in functions. Help() function: The help() function is used to display the documentation string and also facilitates you to see the help related to modules, keywords, attributes, etc. Dir() function: The dir() function is used to display the defined symbols. Q46. Whenever Python exits, why isn’t all the memory de-allocated? Ans: Whenever Python exits, especially those Python modules which are having circular references to other objects or the objects that are referenced from the global namespaces are not always de-allocated or freed. It is impossible to de-allocate those portions of memory that are reserved by the C library. On exit, because of having its own efficient clean up mechanism, Python would try to de-allocate/destroy every other object. Q47. What is a dictionary in Python? Ans: The built-in datatypes in Python is called dictionary. It defines one-to-one relationship between keys and values. Dictionaries contain pair of keys and their corresponding values. Dictionaries are indexed by keys. Let’s take an example: The following example contains some keys. Country, Capital & PM. Their corresponding values are India, Delhi and Modi respectively. 1 dict={'Country':'India','Capital':'Delhi','PM':'Modi'} 1 print dict[Country] Output:India 1 print dict[Capital] Output:Delhi 1 print dict[PM] Output:Modi Q48. How can the ternary operators be used in Python? Ans: The Ternary operator is the operator that is used to show the conditional statements. This consists of the true or false values with a statement that has to be evaluated for it. Syntax: The Ternary operator will be given as: [on_true] if [expression] else [on_false]x, y = 25, 50big = x if x < y else y Example: The expression gets evaluated like if x<y else y, in this case if x<y is true then the value is returned as big=x and if it is incorrect then big=y will be sent as a result. Q50. What does len() do? Ans: It is used to determine the length of a string, a list, an array, etc. Example: 1 2 stg='ABCD' len(stg) Output:4 Q51. Explain split(), sub(), subn() methods of “re” module in Python. Ans: To modify the strings, Python’s “re” module is providing 3 methods. They are: split() – uses a regex pattern to “split” a given string into a list. sub() – finds all substrings where the regex pattern matches and then replace them with a different string subn() – it is similar to sub() and also returns the new string along with the no. of replacements. Q52. What are negative indexes and why are they used? Ans: The sequences in Python are indexed and it consists of the positive as well as negative numbers. The numbers that are positive uses ‘0’ that is uses as first index and ‘1’ as the second index and the process goes on like that. The index for the negative number starts from ‘-1’ that represents the last index in the sequence and ‘-2’ as the penultimate index and the sequence carries forward like the positive number. The negative index is used to remove any new-line spaces from the string and allow the string to except the last character that is given as S[:-1]. The negative index is also used to show the index to represent the string in correct order. Q53. What are Python packages? Ans: Python packages are namespaces containing multiple modules. Q54.How can files be deleted in Python? Ans: To delete a file in Python, you need to import the OS Module. After that, you need to use the os.remove() function. Example: 1 2 import os os.remove("xyz.txt") Q55. What are the built-in types of Python? Ans: Built-in types in Python are as follows – Integers Floating-point Complex numbers Strings Boolean Built-in functions Q58. How to remove values to a Python array? Ans: Array elements can be removed using pop() or remove() method. The difference between these two functions is that the former returns the deleted value whereas the latter does not. Q59. Does Python have OOps concepts? Ans: Python is an object-oriented programming language. This means that any program can be solved in Python by creating an object model. However, Python can be treated as a procedural as well as structural language. Check out these AI and ML courses by E & ICT Academy NIT Warangal to learn Python usage in AI ML and build a successful career. Q60. What is the difference between deep and shallow copy? Ans: Shallow copy is used when a new instance type gets created and it keeps the values that are copied in the new instance. Shallow copy is used to copy the reference pointers just like it copies the values. These references point to the original objects and the changes made in any member of the class will also affect the original copy of it. Shallow copy allows faster execution of the program and it depends on the size of the data that is used. Deep copy is used to store the values that are already copied. Deep copy doesn’t copy the reference pointers to the objects. It makes the reference to an object and the new object that is pointed by some other object gets stored. The changes made in the original copy won’t affect any other copy that uses the object. Deep copy makes execution of the program slower due to making certain copies for each object that is been called. Q61. How is Multithreading achieved in Python? Ans: Python has a multi-threading package but if you want to multi-thread to speed your code up, then it’s usually not a good idea to use it. Python has a construct called the Global Interpreter Lock (GIL). The GIL makes sure that only one of your ‘threads’ can execute at any one time. A thread acquires the GIL, does a little work, then passes the GIL onto the next thread. This happens very quickly so to the human eye it may seem like your threads are executing in parallel, but they are really just taking turns using the same CPU core. All this GIL passing adds overhead to execution. This means that if you want to make your code run faster then using the threading package often isn’t a good idea. Q62. What is the process of compilation and linking in Python? Ans: The compiling and linking allow the new extensions to be compiled properly without any error and the linking can be done only when it passes the compiled procedure. If the dynamic loading is used then it depends on the style that is being provided with the system. The Python interpreter can be used to provide the dynamic loading of the configuration setup files and will rebuild the interpreter. The steps that are required in this as: Create a file with any name and in any language that is supported by the compiler of your system. For example file.c or file.cpp Place this file in the Modules/ directory of the distribution which is getting used. Add a line in the file Setup.local that is present in the Modules/ directory. Run the file using spam file.o After a successful run of this rebuild the interpreter by using the make command on the top-level directory. If the file is changed then run rebuildMakefile by using the command as ‘make Makefile’. Q63. What are Python libraries? Name a few of them. Python libraries are a collection of Python packages. Some of the majorly used Python libraries are – Numpy, Pandas, Matplotlib, Scikit-learn and many more. Q64. What is split used for? The split() method is used to separate a given String in Python. Q65. How to import modules in Python? Modules can be imported using the import keyword. You can import modules in three ways- Example: 1 2 3 import array #importing using the original module name import array as arr # importing using an alias name from array import * #imports everything present in the array module Next, in this Python Interview Questions blog, let’s have a look at Object Oriented Concepts in Python. OOPS Python Interview Questions Q66. Explain Inheritance in Python with an example. Ans: Inheritance allows One class to gain all the members(say attributes and methods) of another class. Inheritance provides code reusability, makes it easier to create and maintain an application. The class from which we are inheriting is called super-class and the class that is inherited is called a derived / child class. They are different types of inheritance supported by Python: Single Inheritance – where a derived class acquires the members of a single super class. Multi-level inheritance – a derived class d1 in inherited from base class base1, and d2 are inherited from base2. Hierarchical inheritance – from one base class you can inherit any number of child classes Multiple inheritance – a derived class is inherited from more than one base class. Q67. How are classes created in Python? Ans: Class in Python is created using the class keyword. Example: 1 2 3 4 5 class Employee: def __init__(self, name): self.name = name E1=Employee("abc") print(E1.name) Output: abc Q68. What is monkey patching in Python? Ans: In Python, the term monkey patch only refers to dynamic modifications of a class or module at run-time. Consider the below example: 1 2 3 4 # m.py class MyClass: def f(self): print "f()" We can then run the monkey-patch testing like this: 1 2 3 4 5 6 7 import m def monkey_f(self): print "monkey_f()" m.MyClass.f = monkey_f obj = m.MyClass() obj.f() The output will be as below: monkey_f() As we can see, we did make some changes in the behavior of f() in MyClass using the function we defined, monkey_f(), outside of the module m. Q69. Does Python support multiple inheritance? Ans: Multiple inheritance means that a class can be derived from more than one parent classes. Python does support multiple inheritance, unlike Java. Q70. What is Polymorphism in Python? Ans: Polymorphism means the ability to take multiple forms. So, for instance, if the parent class has a method named ABC then the child class also can have a method with the same name ABC having its own parameters and variables. Python allows polymorphism. Q71. Define encapsulation in Python? Ans: Encapsulation means binding the code and the data together. A Python class in an example of encapsulation. Q72. How do you do data abstraction in Python? Ans: Data Abstraction is providing only the required details and hiding the implementation from the world. It can be achieved in Python by using interfaces and abstract classes. Q73.Does Python make use of access specifiers? Ans: Python does not deprive access to an instance variable or function. Python lays down the concept of prefixing the name of the variable, function or method with a single or double underscore to imitate the behavior of protected and private access specifiers. Q74. How to create an empty class in Python? Ans: An empty class is a class that does not have any code defined within its block. It can be created using the pass keyword. However, you can create objects of this class outside the class itself. IN Python THE PASS command does nothing when its executed. it’s a null statement. For example- 1 2 3 4 5 class a: pass obj=a() obj.name="xyz" print("Name = ",obj.name) Output: Name = xyz Q75. What does an object() do? Ans: It returns a featureless object that is a base for all classes. Also, it does not take any parameters. Next, let us have a look at some Basic Python Programs in these Python Interview Questions. Basic Python Programs – Python Interview Questions Q76. Write a program in Python to execute the Bubble sort algorithm. 1 2 3 4 5 6 7 8 9 10 def bs(a): # a = name of list b=len(a)-1nbsp; # minus 1 because we always compare 2 adjacent values for x in range(b): for y in range(b-x): a[y]=a[y+1] a=[32,5,3,6,7,54,87] bs(a) Output: [3, 5, 6, 7, 32, 54, 87] Q77. Write a program in Python to produce Star triangle. 1 2 3 4 def pyfunc(r): for x in range(r): print(' '*(r-x-1)+'*'*(2*x+1)) pyfunc(9) Output: * *** ***** ******* ********* *********** ************* *************** ***************** Q78. Write a program to produce Fibonacci series in Python. 1 2 3 4 5 6 7 8 9 10 11 12 # Enter number of terms needednbsp;#0,1,1,2,3,5.... a=int(input("Enter the terms")) f=0;#first element of series s=1#second element of series if a=0: print("The requested series is",f) else: print(f,s,end=" ") for x in range(2,a): print(next,end=" ") f=s s=next Output: Enter the terms 5 0 1 1 2 3 Q79. Write a program in Python to check if a number is prime. 1 2 3 4 5 6 7 8 9 10 a=int(input("enter number")) if a=1: for x in range(2,a): if(a%x)==0: print("not prime") break else: print("Prime") else: print("not prime") Output: enter number 3 Prime Q80. Write a program in Python to check if a sequence is a Palindrome. 1 2 3 4 5 6 a=input("enter sequence") b=a[::-1] if a==b: print("palindrome") else: print("Not a Palindrome") Output: enter sequence 323 palindrome Q81. Write a one-liner that will count the number of capital letters in a file. Your code should work even if the file is too big to fit in memory. Ans: Let us first write a multiple line solution and then convert it to one-liner code. 1 2 3 4 5 6 with open(SOME_LARGE_FILE) as fh: count = 0 text = fh.read() for character in text: if character.isupper(): count += 1 We will now try to transform this into a single line. 1 count sum(1 for line in fh for character in line if character.isupper()) Q82. Write a sorting algorithm for a numerical dataset in Python. Ans: The following code can be used to sort a list in Python: 1 2 3 4 list = ["1", "4", "0", "6", "9"] list = [int(i) for i in list] list.sort() print (list) Q83. Looking at the below code, write down the final values of A0, A1, …An. 1 2 3 4 5 6 7 A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5))) A1 = range(10)A2 = sorted([i for i in A1 if i in A0]) A3 = sorted([A0[s] for s in A0]) A4 = [i for i in A1 if i in A3] A5 = {i:i*i for i in A1} A6 = [[i,i*i] for i in A1] print(A0,A1,A2,A3,A4,A5,A6) Ans: The following will be the final outputs of A0, A1, … A6 A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4} # the order may vary A1 = range(0, 10) A2 = [] A3 = [1, 2, 3, 4, 5] A4 = [1, 2, 3, 4, 5] A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]] Next, in this Python Interview Questions let's have a look at some Python Libraries Python Libraries – Python Interview Questions Q84. Explain what Flask is and its benefits? Ans: Flask is a web microframework for Python based on “Werkzeug, Jinja2 and good intentions” BSD license. Werkzeug and Jinja2 are two of their dependencies. This means it will have little to no dependencies on external libraries. It makes the framework light while there is a little dependency to update and fewer security bugs. A session basically allows you to remember information from one request to another. In a flask, a session uses a signed cookie so the user can look at the session contents and modify them. The user can modify the session if only it has the secret key Flask.secret_key. Q85. Is Django better than Flask? Ans: Django and Flask map the URL’s or addresses typed in the web browsers to functions in Python. Flask is much simpler compared to Django but, Flask does not do a lot for you meaning you will need to specify the details, whereas Django does a lot for you wherein you would not need to do much work. Django consists of prewritten code, which the user will need to analyze whereas Flask gives the users to create their own code, therefore, making it simpler to understand the code. Technically both are equally good and both contain their own pros and cons. Q86. Mention the differences between Django, Pyramid and Flask. Ans: Flask is a “microframework” primarily build for a small application with simpler requirements. In flask, you have to use external libraries. Flask is ready to use. Pyramid is built for larger applications. It provides flexibility and lets the developer use the right tools for their project. The developer can choose the database, URL structure, templating style and more. Pyramid is heavy configurable. Django can also be used for larger applications just like Pyramid. It includes an ORM. Q87. Discuss Django architecture. Ans: Django MVT Pattern: Django Architecture - Python Interview Questions - EdurekaFigure: Python Interview Questions – Django Architecture The developer provides the Model, the view and the template then just maps it to a URL and Django does the magic to serve it to the user. Q88. Explain how you can set up the Database in Django. Ans: You can use the command edit mysite/setting.py, it is a normal Python module with module level representing Django settings. Django uses SQLite by default; it is easy for Django users as such it won’t require any other type of installation. In the case your database choice is different that you have to the following keys in the DATABASE ‘default’ item to match your database connection settings. Engines: you can change the database by using ‘django.db.backends.sqlite3’ , ‘django.db.backeneds.mysql’, ‘django.db.backends.postgresql_psycopg2’, ‘django.db.backends.oracle’ and so on Name: The name of your database. In the case if you are using SQLite as your database, in that case, database will be a file on your computer, Name should be a full absolute path, including the file name of that file. If you are not choosing SQLite as your database then settings like Password, Host, User, etc. must be added. Django uses SQLite as a default database, it stores data as a single file in the filesystem. If you do have a database server—PostgreSQL, MySQL, Oracle, MSSQL—and want to use it rather than SQLite, then use your database’s administration tools to create a new database for your Django project. Either way, with your (empty) database in place, all that remains is to tell Django how to use it. This is where your project’s settings.py file comes in. We will add the following lines of code to the setting.py file: 1 2 3 4 5 6 DATABASES = { 'default': { 'ENGINE' : 'django.db.backends.sqlite3', 'NAME' : os.path.join(BASE_DIR, 'db.sqlite3'), } } Q89. Give an example how you can write a VIEW in Django? Ans: This is how we can use write a view in Django: 1 2 3 4 5 6 7 from django.http import HttpResponse import datetime def Current_datetime(request): now = datetime.datetime.now() html = "It is now %s/body/html % now return HttpResponse(html) Returns the current date and time, as an HTML document Q90. Mention what the Django templates consist of. Ans: The template is a simple text file. It can create any text-based format like XML, CSV, HTML, etc. A template contains variables that get replaced with values when the template is evaluated and tags (% tag %) that control the logic of the template. Django Template - Python Interview Questions - EdurekaFigure: Python Interview Questions – Django Template Q91. Explain the use of session in Django framework? Ans: Django provides a session that lets you store and retrieve data on a per-site-visitor basis. Django abstracts the process of sending and receiving cookies, by placing a session ID cookie on the client side, and storing all the related data on the server side. Django Framework - Python Interview Questions - EdurekaFigure: Python Interview Questions – Django Framework So the data itself is not stored client side. This is nice from a security perspective. Q92. List out the inheritance styles in Django. Ans: In Django, there are three possible inheritance styles: Abstract Base Classes: This style is used when you only want parent’s class to hold information that you don’t want to type out for each child model. Multi-table Inheritance: This style is used If you are sub-classing an existing model and need each model to have its own database table. Proxy models: You can use this model, If you only want to modify the Python level behavior of the model, without changing the model’s fields. Next in this Python Interview Question blog, let’s have a look at questions related to Web Scraping Web Scraping – Python Interview Questions Q93. How To Save An Image Locally Using Python Whose URL Address I Already Know? Ans: We will use the following code to save an image locally from an URL address 1 2 import urllib.request urllib.request.urlretrieve("URL", "local-filename.jpg") Q94. How can you Get the Google cache age of any URL or web page? Ans: Use the following URL format: http://webcache.googleusercontent.com/search?q=cache:URLGOESHERE Be sure to replace “URLGOESHERE” with the proper web address of the page or site whose cache you want to retrieve and see the time for. For example, to check the Google Webcache age of edureka.co you’d use the following URL: http://webcache.googleusercontent.com/search?q=cache:edureka.co Q95. You are required to scrap data from IMDb top 250 movies page. It should only have fields movie name, year, and rating. Ans: We will use the following lines of code: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 from bs4 import BeautifulSoup import requests import sys url = 'http://www.imdb.com/chart/top' response = requests.get(url) soup = BeautifulSoup(response.text) tr = soup.findChildren("tr") tr = iter(tr) next(tr) for movie in tr: title = movie.find('td', {'class': 'titleColumn'} ).find('a').contents[0] year = movie.find('td', {'class': 'titleColumn'} ).find('span', {'class': 'secondaryInfo'}).contents[0] rating = movie.find('td', {'class': 'ratingColumn imdbRating'} ).find('strong').contents[0] row = title + ' - ' + year + ' ' + ' ' + rating print(row) The above code will help scrap data from IMDb’s top 250 list Next in this Python Interview Questions blog, let’s have a look at questions related to Data Analysis in Python. Data Analysis – Python Interview Questions Q96. What is map function in Python? Ans: map function executes the function given as the first argument on all the elements of the iterable given as the second argument. If the function given takes in more than 1 arguments, then many iterables are given. #Follow the link to know more similar functions. Q97. Is Python numpy better than lists? Ans: We use Python numpy array instead of a list because of the below three reasons: Less Memory Fast Convenient For more information on these parameters, you can refer to this section – Numpy Vs List. Q98. How to get indices of N maximum values in a NumPy array? Ans: We can get the indices of N maximum values in a NumPy array using the below code: 1 2 3 import numpy as np arr = np.array([1, 3, 2, 4, 5]) print(arr.argsort()[-3:][::-1]) Output [ 4 3 1 ] Q99. How do you calculate percentiles with Python/ NumPy? Ans: We can calculate percentiles with the following code 1 2 3 4 import numpy as np a = np.array([1,2,3,4,5]) p = np.percentile(a, 50) #Returns 50th percentile, e.g. median print(p) Output:3 Q100. What is the difference between NumPy and SciPy? Ans: NumPy SciPy It refers to Numerical Python. It refers to Scientific Python. It has fewer new scientific computing features. Most new scientific computing features belong in SciPy. It contains less linear algebra functions. It has more fully-featured versions of the linear algebra modules, as well as many other numerical algorithms. NumPy has a faster processing speed. SciPy on the other hand has slower computational speed. Q101. How do you make 3D plots/visualizations using NumPy/SciPy? Ans: Like 2D plotting, 3D graphics is beyond the scope of NumPy and SciPy, but just as in the 2D case, packages exist that integrate with NumPy. Matplotlib provides basic 3D plotting in the mplot3d subpackage, whereas Mayavi provides a wide range of high-quality 3D visualization features, utilizing the powerful VTK engine. Next in this Python Interview Questions blog, let’s have a look at some MCQs Multiple Choice Questions (MCQ) – Python Interview Questions Q102. Which of the following statements create a dictionary? (Multiple Correct Answers Possible) a) d = {} b) d = {“john”:40, “peter”:45} c) d = {40:”john”, 45:”peter”} d) d = (40:”john”, 45:”50”) Answer: b, c & d. Dictionaries are created by specifying keys and values. Q103. Which one of these is floor division? a) / b) // c) % d) None of the mentioned Answer: b) // When both of the operands are integer then Python chops out the fraction part and gives you the round off value, to get the accurate answer use floor division. For ex, 5/2 = 2.5 but both of the operands are integer so answer of this expression in Python is 2. To get the 2.5 as the answer, use floor division using //. So, 5//2 = 2.5 Q104. What is the maximum possible length of an identifier? a) 31 characters b) 63 characters c) 79 characters d) None of the above Answer: d) None of the above Identifiers can be of any length. Q105. Why are local variable names beginning with an underscore discouraged? a) they are used to indicate a private variables of a class b) they confuse the interpreter c) they are used to indicate global variables d) they slow down execution Answer: a) they are used to indicate a private variable of a class As Python has no concept of private variables, leading underscores are used to indicate variables that must not be accessed from outside the class. Q106. Which of the following is an invalid statement? a) abc = 1,000,000 b) a b c = 1000 2000 3000 c) a,b,c = 1000, 2000, 3000 d) a_b_c = 1,000,000 Answer: b) a b c = 1000 2000 3000 Spaces are not allowed in variable names. Q107. What is the output of the following? 1 2 3 4 5 6 7 try: if '1' != 1: raise "someError" else: print("someError has not occured") except "someError": print ("someError has occured") a) someError has occured b) someError has not occured c) invalid code d) none of the above Answer: c) invalid code A new exception class must inherit from a BaseException. There is no such inheritance here. Q108. Suppose list1 is [2, 33, 222, 14, 25], What is list1[-1] ? a) Error b) None c) 25 d) 2 Answer: c) 25 The index -1 corresponds to the last index in the list. Q109. To open a file c:scores.txt for writing, we use a) outfile = open(“c:scores.txt”, “r”) b) outfile = open(“c:scores.txt”, “w”) c) outfile = open(file = “c:scores.txt”, “r”) d) outfile = open(file = “c:scores.txt”, “o”) Answer: b) The location contains double slashes ( ) and w is used to indicate that file is being written to. Q110. What is the output of the following? 1 2 3 4 5 6 7 8 f = None for i in range (5): with open("data.txt", "w") as f: if (i > 2): break print f.closed a) True b) False c) None d) Error Answer: a) True The WITH statement when used with open file guarantees that the file object is closed when the with block exits. Q111. When will the else part of try-except-else be executed? a) always b) when an exception occurs c) when no exception occurs d) when an exception occurs into except block Answer: c) when no exception occurs The else part is executed when no exception occurs. 1. What is Python? What are the benefits of using Python Python is a high-level, interpreted, general-purpose programming language. Being a general-purpose language, it can be used to build almost any type of application with the right tools/libraries. Additionally, Python supports objects, modules, threads, exception-handling, and automatic memory management which help in modelling real-world problems and building applications to solve these problems. Benefits of using Python: Python is a general-purpose programming language that has a simple, easy-to-learn syntax that emphasizes readability and therefore reduces the cost of program maintenance. Moreover, the language is capable of scripting, is completely open-source, and supports third-party packages encouraging modularity and code reuse. Its high-level data structures, combined with dynamic typing and dynamic binding, attract a huge community of developers for Rapid Application Development and deployment. 2. What is a dynamically typed language? Before we understand a dynamically typed language, we should learn about what typing is. Typing refers to type-checking in programming languages. In a strongly-typed language, such as Python, "1" + 2 will result in a type error since these languages don't allow for "type-coercion" (implicit conversion of data types). On the other hand, a weakly-typed language, such as Javascript, will simply output "12" as result. Type-checking can be done at two stages - Static - Data Types are checked before execution. Dynamic - Data Types are checked during execution. Python is an interpreted language, executes each statement line by line and thus type-checking is done on the fly, during execution. Hence, Python is a Dynamically Typed Language. 3. What is an Interpreted language? An Interpreted language executes its statements line by line. Languages such as Python, Javascript, R, PHP, and Ruby are prime examples of Interpreted languages. Programs written in an interpreted language runs directly from the source code, with no intermediary compilation step. 5. What is Scope in Python? Every object in Python functions within a scope. A scope is a block of code where an object in Python remains relevant. Namespaces uniquely identify all the objects inside a program. However, these namespaces also have a scope defined for them where you could use their objects without any prefix. A few examples of scope created during code execution in Python are as follows: A local scope refers to the local objects available in the current function. A global scope refers to the objects available throughout the code execution since their inception. A module-level scope refers to the global objects of the current module accessible in the program. An outermost scope refers to all the built-in names callable in the program. The objects in this scope are searched last to find the name referenced. Note: Local scope objects can be synced with global scope objects using keywords such as global. 6. What are lists and tuples? What is the key difference between the two? Lists and Tuples are both sequence data types that can store a collection of objects in Python. The objects stored in both sequences can have different data types. Lists are represented with square brackets ['sara', 6, 0.19], while tuples are represented with parantheses ('ansh', 5, 0.97). But what is the real difference between the two? The key difference between the two is that while lists are mutable, tuples on the other hand are immutable objects. This means that lists can be modified, appended or sliced on the go but tuples remain constant and cannot be modified in any manner. You can run the following example on Python IDLE to confirm the difference: my_tuple = ('sara', 6, 5, 0.97) my_list = ['sara', 6, 5, 0.97] print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'sara' my_tuple[0] = 'ansh' # modifying tuple => throws an error my_list[0] = 'ansh' # modifying list => list modified print(my_tuple[0]) # output => 'sara' print(my_list[0]) # output => 'ansh' logo Practice Problems Solve these problems to ace this concept Lists Easy 10.50 Mins Solve Tuples Easy 12.9 Mins Solve 7. What are the common built-in data types in Python? There are several built-in data types in Python. Although, Python doesn't require data types to be defined explicitly during variable declarations type errors are likely to occur if the knowledge of data types and their compatibility with each other are neglected. Python provides type() and isinstance() functions to check the type of these variables. These data types can be grouped into the following categories- None Type: None keyword represents the null values in Python. Boolean equality operation can be performed using these NoneType objects. Class Name Description NoneType Represents the NULL values in Python. Numeric Types: There are three distinct numeric types - integers, floating-point numbers, and complex numbers. Additionally, booleans are a sub-type of integers. Class Name Description int Stores integer literals including hex, octal and binary numbers as integers float Stores literals containing decimal values and/or exponent signs as floating-point numbers complex Stores complex numbers in the form (A + Bj) and has attributes: real and imag bool Stores boolean value (True or False). Note: The standard library also includes fractions to store rational numbers and decimal to store floating-point numbers with user-defined precision. Sequence Types: According to Python Docs, there are three basic Sequence Types - lists, tuples, and range objects. Sequence types have the in and not in operators defined for their traversing their elements. These operators share the same priority as the comparison operations. Class Name Description list Mutable sequence used to store collection of items. tuple Immutable sequence used to store collection of items. range Represents an immutable sequence of numbers generated during execution. str Immutable sequence of Unicode code points to store textual data. Note: The standard library also includes additional types for processing: 1. Binary data such as bytearray bytes memoryview , and 2. Text strings such as str. Mapping Types: A mapping object can map hashable values to random objects in Python. Mappings objects are mutable and there is currently only one standard mapping type, the dictionary. Class Name Description dict Stores comma-separated list of key: value pairs Set Types: Currently, Python has two built-in set types - set and frozenset. set type is mutable and supports methods like add() and remove(). frozenset type is immutable and can't be modified after creation. Class Name Description set Mutable unordered collection of distinct hashable objects. frozenset Immutable collection of distinct hashable objects. Note: set is mutable and thus cannot be used as key for a dictionary. On the other hand, frozenset is immutable and thus, hashable, and can be used as a dictionary key or as an element of another set. Modules: Module is an additional built-in type supported by the Python Interpreter. It supports one special operation, i.e., attribute access: mymod.myobj, where mymod is a module and myobj references a name defined in m's symbol table. The module's symbol table resides in a very special attribute of the module __dict__, but direct assignment to this module is neither possible nor recommended. Callable Types: Callable types are the types to which function call can be applied. They can be user-defined functions, instance methods, generator functions, and some other built-in functions, methods and classes. Refer to the documentation at docs.Python.org for a detailed view of the callable types. logo Practice Problems Solve these problems to ace this concept Variables and Types Very Easy 12.55 Mins Solve 8. What is pass in Python? The pass keyword represents a null operation in Python. It is generally used for the purpose of filling up empty blocks of code which may execute during runtime but has yet to be written. Without the pass statement in the following code, we may run into some errors during code execution. def myEmptyFunc(): # do nothing pass myEmptyFunc() # nothing happens ## Without the pass keyword # File "<stdin>", line 3 # IndentationError: expected an indented block 9. What are modules and packages in Python? Python packages and Python modules are two mechanisms that allow for modular programming in Python. Modularizing has several advantages - Simplicity: Working on a single module helps you focus on a relatively small portion of the problem at hand. This makes development easier and less error-prone. Maintainability: Modules are designed to enforce logical boundaries between different problem domains. If they are written in a manner that reduces interdependency, it is less likely that modifications in a module might impact other parts of the program. Reusability: Functions defined in a module can be easily reused by other parts of the application. Scoping: Modules typically define a separate namespace, which helps avoid confusion between identifiers from other parts of the program. Modules, in general, are simply Python files with a .py extension and can have a set of functions, classes, or variables defined and implemented. They can be imported and initialized once using the import statement. If partial functionality is needed, import the requisite classes or functions using from foo import bar. Packages allow for hierarchial structuring of the module namespace using dot notation. As, modules help avoid clashes between global variable names, in a similar manner, packages help avoid clashes between module names. Creating a package is easy since it makes use of the system's inherent file structure. So just stuff the modules into a folder and there you have it, the folder name as the package name. Importing a module or its contents from this package requires the package name as prefix to the module name joined by a dot. Note: You can technically import the package as well, but alas, it doesn't import the modules within the package to the local namespace, thus, it is practically useless. 10. What are global, protected and private attributes in Python? Global variables are public variables that are defined in the global scope. To use the variable in the global scope inside a function, we use the global keyword. Protected attributes are attributes defined with an underscore prefixed to their identifier eg. _sara. They can still be accessed and modified from outside the class they are defined in but a responsible developer should refrain from doing so. Private attributes are attributes with double underscore prefixed to their identifier eg. __ansh. They cannot be accessed or modified from the outside directly and will result in an AttributeError if such an attempt is made. 11. What is the use of self in Python? Self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in Python. It binds the attributes with the given arguments. self is used in different places and often thought to be a keyword. But unlike in C++, self is not a keyword in Python. 12. What is __init__? __init__ is a contructor method in Python and is automatically called to allocate memory when a new object/instance is created. All classes have a __init__ method associated with them. It helps in distinguishing methods and attributes of a class from local variables. # class definition class Student: def __init__(self, fname, lname, age, section): self.firstname = fname self.lastname = lname self.age = age self.section = section # creating a new object stu1 = Student("Sara", "Ansh", 22, "A2") 13. What is break, continue and pass in Python? Break The break statement terminates the loop immediately and the control flows to the statement after the body of the loop. Continue The continue statement terminates the current iteration of the statement, skips the rest of the code in the current iteration and the control flows to the next iteration of the loop. Pass As explained above, the pass keyword in Python is generally used to fill up empty blocks and is similar to an empty statement represented by a semi-colon in languages such as Java, C++, Javascript, etc. pat = [1, 3, 2, 1, 2, 3, 1, 0, 1, 3] for p in pat: pass if (p == 0): current = p break elif (p % 2 == 0): continue print(p) # output => 1 3 1 3 1 print(current) # output => 0 14. What are unit tests in Python? Unit test is a unit testing framework of Python. Unit testing means testing different components of software separately. Can you think about why unit testing is important? Imagine a scenario, you are building software that uses three components namely A, B, and C. Now, suppose your software breaks at a point time. How will you find which component was responsible for breaking the software? Maybe it was component A that failed, which in turn failed component B, and this actually failed the software. There can be many such combinations. This is why it is necessary to test each and every component properly so that we know which component might be highly responsible for the failure of the software. 15. What is docstring in Python? Documentation string or docstring is a multiline string used to document a specific code segment. The docstring should describe what the function or method does. 16. What is slicing in Python? As the name suggests, ‘slicing’ is taking parts of. Syntax for slicing is [start : stop : step] start is the starting index from where to slice a list or tuple stop is the ending index or where to sop. step is the number of steps to jump. Default value for start is 0, stop is number of items, step is 1. Slicing can be done on strings, arrays, lists, and tuples. numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(numbers[1 : : 2]) #output : [2, 4, 6, 8, 10] 17. Explain how can you make a Python Script executable on Unix? Script file must begin with #!/usr/bin/env Python 18. What is the difference between Python Arrays and lists? Arrays in Python can only contain elements of same data types i.e., data type of array should be homogeneous. It is a thin wrapper around C language arrays and consumes far less memory than lists. Lists in Python can contain elements of different data types i.e., data type of lists can be heterogeneous. It has the disadvantage of consuming large memory. import array a = array.array('i', [1, 2, 3]) for i in a: print(i, end=' ') #OUTPUT: 1 2 3 a = array.array('i', [1, 2, 'string']) #OUTPUT: TypeError: an integer is required (got type str) a = [1, 2, 'string'] for i in a: print(i, end=' ') #OUTPUT: 1 2 string Python Interview Questions for Experienced 19. How is memory managed in Python? Memory management in Python is handled by the Python Memory Manager. The memory allocated by the manager is in form of a private heap space dedicated to Python. All Python objects are stored in this heap and being private, it is inaccessible to the programmer. Though, Python does provide some core API functions to work upon the private heap space. Additionally, Python has an in-built garbage collection to recycle the unused memory for the private heap space. 20. What are Python namespaces? Why are they used? A namespace in Python ensures that object names in a program are unique and can be used without any conflict. Python implements these namespaces as dictionaries with 'name as key' mapped to a corresponding 'object as value'. This allows for multiple namespaces to use the same name and map it to a separate object. A few examples of namespaces are as follows: Local Namespace includes local names inside a function. the namespace is temporarily created for a function call and gets cleared when the function returns. Global Namespace includes names from various imported packages/ modules that are being used in the current project. This namespace is created when the package is imported in the script and lasts until the execution of the script. Built-in Namespace includes built-in functions of core Python and built-in names for various types of exceptions. The lifecycle of a namespace depends upon the scope of objects they are mapped to. If the scope of an object ends, the lifecycle of that namespace comes to an end. Hence, it isn't possible to access inner namespace objects from an outer namespace. 21. What is Scope Resolution in Python? Sometimes objects within the same scope have the same name but function differently. In such cases, scope resolution comes into play in Python automatically. A few examples of such behavior are: Python modules namely 'math' and 'cmath' have a lot of functions that are common to both of them - log10(), acos(), exp() etc. To resolve this ambiguity, it is necessary to prefix them with their respective module, like math.exp() and cmath.exp(). Consider the code below, an object temp has been initialized to 10 globally and then to 20 on function call. However, the function call didn't change the value of the temp globally. Here, we can observe that Python draws a clear line between global and local variables, treating their namespaces as separate identities. temp = 10 # global-scope variable def func(): temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 10 This behavior can be overridden using the global keyword inside the function, as shown in the following example: temp = 10 # global-scope variable def func(): global temp temp = 20 # local-scope variable print(temp) print(temp) # output => 10 func() # output => 20 print(temp) # output => 20 22. What are decorators in Python? Decorators in Python are essentially functions that add functionality to an existing function in Python without changing the structure of the function itself. They are represented the @decorator_name in Python and are called in a bottom-up fashion. For example: # decorator function to convert to lowercase def lowercase_decorator(function): def wrapper(): func = function() string_lowercase = func.lower() return string_lowercase return wrapper # decorator function to split words def splitter_decorator(function): def wrapper(): func = function() string_split = func.split() return string_split return wrapper @splitter_decorator # this is executed next @lowercase_decorator # this is executed first def hello(): return 'Hello World' hello() # output => [ 'hello' , 'world' ] The beauty of the decorators lies in the fact that besides adding functionality to the output of the method, they can even accept arguments for functions and can further modify those arguments before passing it to the function itself. The inner nested function, i.e. 'wrapper' function, plays a significant role here. It is implemented to enforce encapsulation and thus, keep itself hidden from the global scope. # decorator function to capitalize names def names_decorator(function): def wrapper(arg1, arg2): arg1 = arg1.capitalize() arg2 = arg2.capitalize() string_hello = function(arg1, arg2) return string_hello return wrapper @names_decorator def say_hello(name1, name2): return 'Hello ' + name1 + '! Hello ' + name2 + '!' say_hello('sara', 'ansh') # output => 'Hello Sara! Hello Ansh!' 23. What are Dict and List comprehensions? Python comprehensions, like decorators, are syntactic sugar constructs that help build altered and filtered lists, dictionaries, or sets from a given list, dictionary, or set. Using comprehensions saves a lot of time and code that might be considerably more verbose (containing more lines of code). Let's check out some examples, where comprehensions can be truly beneficial: Performing mathematical operations on the entire list my_list = [2, 3, 5, 7, 11] squared_list = [x**2 for x in my_list] # list comprehension # output => [4 , 9 , 25 , 49 , 121] squared_dict = {x:x**2 for x in my_list} # dict comprehension # output => {11: 121, 2: 4 , 3: 9 , 5: 25 , 7: 49} Performing conditional filtering operations on the entire list my_list = [2, 3, 5, 7, 11] squared_list = [x**2 for x in my_list if x%2 != 0] # list comprehension # output => [9 , 25 , 49 , 121] squared_dict = {x:x**2 for x in my_list if x%2 != 0} # dict comprehension # output => {11: 121, 3: 9 , 5: 25 , 7: 49} Combining multiple lists into one Comprehensions allow for multiple iterators and hence, can be used to combine multiple lists into one. a = [1, 2, 3] b = [7, 8, 9] [(x + y) for (x,y) in zip(a,b)] # parallel iterators # output => [8, 10, 12] [(x,y) for x in a for y in b] # nested iterators # output => [(1, 7), (1, 8), (1, 9), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9)] Flattening a multi-dimensional list A similar approach of nested iterators (as above) can be applied to flatten a multi-dimensional list or work upon its inner elements. my_list = [[10,20,30],[40,50,60],[70,80,90]] flattened = [x for temp in my_list for x in temp] # output => [10, 20, 30, 40, 50, 60, 70, 80, 90] Note: List comprehensions have the same effect as the map method in other languages. They follow the mathematical set builder notation rather than map and filter functions in Python. 24. What is lambda in Python? Why is it used? Lambda is an anonymous function in Python, that can accept any number of arguments, but can only have a single expression. It is generally used in situations requiring an anonymous function for a short time period. Lambda functions can be used in either of the two ways: Assigning lambda functions to a variable: mul = lambda a, b : a * b print(mul(2, 5)) # output => 10 Wrapping lambda functions inside another function: def myWrapper(n): return lambda a : a * n mulFive = myWrapper(5) print(mulFive(2)) # output => 10 25. How do you copy an object in Python? In Python, the assignment statement (= operator) does not copy objects. Instead, it creates a binding between the existing object and the target variable name. To create copies of an object in Python, we need to use the copy module. Moreover, there are two ways of creating copies for the given object using the copy module - Shallow Copy is a bit-wise copy of an object. The copied object created has an exact copy of the values in the original object. If either of the values is a reference to other objects, just the reference addresses for the same are copied. Deep Copy copies all values recursively from source to target object, i.e. it even duplicates the objects referenced by the source object. from copy import copy, deepcopy list_1 = [1, 2, [3, 5], 4] ## shallow copy list_2 = copy(list_1) list_2[3] = 7 list_2[2].append(6) list_2 # output => [1, 2, [3, 5, 6], 7] list_1 # output => [1, 2, [3, 5, 6], 4] ## deep copy list_3 = deepcopy(list_1) list_3[3] = 8 list_3[2].append(7) list_3 # output => [1, 2, [3, 5, 6, 7], 8] list_1 # output => [1, 2, [3, 5, 6], 4] 26. What is the difference between xrange and range in Python? xrange() and range() are quite similar in terms of functionality. They both generate a sequence of integers, with the only difference that range() returns a Python list, whereas, xrange() returns an xrange object. So how does that make a difference? It sure does, because unlike range(), xrange() doesn't generate a static list, it creates the value on the go. This technique is commonly used with an object-type generator and has been termed as "yielding". Yielding is crucial in applications where memory is a constraint. Creating a static list as in range() can lead to a Memory Error in such conditions, while, xrange() can handle it optimally by using just enough memory for the generator (significantly less in comparison). for i in xrange(10): # numbers from o to 9 print i # output => 0 1 2 3 4 5 6 7 8 9 for i in xrange(1,10): # numbers from 1 to 9 print i # output => 1 2 3 4 5 6 7 8 9 for i in xrange(1, 10, 2): # skip by two for next print i # output => 1 3 5 7 9 Note: xrange has been deprecated as of Python 3.x. Now range does exactly the same as what xrange used to do in Python 2.x, since it was way better to use xrange() than the original range() function in Python 2.x. 27. What is pickling and unpickling? Python library offers a feature - serialization out of the box. Serializing an object refers to transforming it into a format that can be stored, so as to be able to deserialize it, later on, to obtain the original object. Here, the pickle module comes into play. Pickling: Pickling is the name of the serialization process in Python. Any object in Python can be serialized into a byte stream and dumped as a file in the memory. The process of pickling is compact but pickle objects can be compressed further. Moreover, pickle keeps track of the objects it has serialized and the serialization is portable across versions. The function used for the above process is pickle.dump(). Unpickling: Unpickling is the complete inverse of pickling. It deserializes the byte stream to recreate the objects stored in the file and loads the object to memory. The function used for the above process is pickle.load(). Note: Python has another, more primitive, serialization module called marshall, which exists primarily to support .pyc files in Python and differs significantly from the pickle. 28. What are generators in Python? Generators are functions that return an iterable collection of items, one at a time, in a set manner. Generators, in general, are used to create iterators with a different approach. They employ the use of yield keyword rather than return to return a generator object. Let's try and build a generator for fibonacci numbers - ## generate fibonacci numbers upto n def fib(n): p, q = 0, 1 while(p < n): yield p p, q = q, p + q x = fib(10) # create generator object ## iterating using __next__(), for Python2, use next() x.__next__() # output => 0 x.__next__() # output => 1 x.__next__() # output => 1 x.__next__() # output => 2 x.__next__() # output => 3 x.__next__() # output => 5 x.__next__() # output => 8 x.__next__() # error ## iterating using loop for i in fib(10): print(i) # output => 0 1 1 2 3 5 8 29. What is PythonPATH in Python? PythonPATH is an environment variable which you can set to add additional directories where Python will look for modules and packages. This is especially useful in maintaining Python libraries that you do not wish to install in the global default location. 30. What is the use of help() and dir() functions? help() function in Python is used to display the documentation of modules, classes, functions, keywords, etc. If no parameter is passed to the help() function, then an interactive help utility is launched on the console. dir() function tries to return a valid list of attributes and methods of the object it is called upon. It behaves differently with different objects, as it aims to produce the most relevant data, rather than the complete information. For Modules/Library objects, it returns a list of all attributes, contained in that module. For Class Objects, it returns a list of all valid attributes and base attributes. With no arguments passed, it returns a list of attributes in the current scope. 31. What is the difference between .py and .pyc files? .py files contain the source code of a program. Whereas, .pyc file contains the bytecode of your program. We get bytecode after compilation of .py file (source code). .pyc files are not created for all the files that you run. It is only created for the files that you import. Before executing a Python program Python interpreter checks for the compiled files. If the file is present, the virtual machine executes it. If not found, it checks for .py file. If found, compiles it to .pyc file and then Python virtual machine executes it. Having .pyc file saves you the compilation time. 32. How Python is interpreted? Python as a language is not interpreted or compiled. Interpreted or compiled is the property of the implementation. Python is a bytecode(set of interpreter readable instructions) interpreted generally. Source code is a file with .py extension. Python compiles the source code to a set of instructions for a virtual machine. The Python interpreter is an implementation of that virtual machine. This intermediate format is called “bytecode”. .py source code is first compiled to give .pyc which is bytecode. This bytecode can be then interpreted by the official CPython or JIT(Just in Time compiler) compiled by PyPy. 33. How are arguments passed by value or by reference in Python? Pass by value: Copy of the actual object is passed. Changing the value of the copy of the object will not change the value of the original object. Pass by reference: Reference to the actual object is passed. Changing the value of the new object will change the value of the original object. In Python, arguments are passed by reference, i.e., reference to the actual object is passed. def appendNumber(arr): arr.append(4) arr = [1, 2, 3] print(arr) #Output: => [1, 2, 3] appendNumber(arr) print(arr) #Output: => [1, 2, 3, 4] 34. What are iterators in Python? An iterator is an object. It remembers its state i.e., where it is during iteration (see code below to see how) __iter__() method initializes an iterator. It has a __next__() method which returns the next item in iteration and points to the next element. Upon reaching the end of iterable object __next__() must return StopIteration exception. It is also self-iterable. Iterators are objects with which we can iterate over iterable objects like lists, strings, etc. class ArrayList: def __init__(self, number_list): self.numbers = number_list def __iter__(self): self.pos = 0 return self def __next__(self): if(self.pos < len(self.numbers)): self.pos += 1 return self.numbers[self.pos - 1] else: raise StopIteration array_obj = ArrayList([1, 2, 3]) it = iter(array_obj) print(next(it)) #output: 2 print(next(it)) #output: 3 print(next(it)) #Throws Exception #Traceback (most recent call last): #... #StopIteration logo Practice Problems Solve these problems to ace this concept Itertools: Terminating Iterators Easy 15.24 Mins Solve 35. Explain how to delete a file in Python? Use command os.remove(file_name) import os os.remove("ChangedFile.csv") print("File Removed!") 36. Explain split() and join() functions in Python? You can use split() function to split a string based on a delimiter to a list of strings. You can use join() function to join a list of strings based on a delimiter to give a single string. string = "This is a string." string_list = string.split(' ') #delimiter is ‘space’ character or ‘ ‘ print(string_list) #output: ['This', 'is', 'a', 'string.'] print(' '.join(string_list)) #output: This is a string. 37. What does *args and **kwargs mean? *args *args is a special syntax used in the function definition to pass variable-length arguments. “*” means variable length and “args” is the name used by convention. You can use any other. def multiply(a, b, *argv): mul = a * b for num in argv: mul *= num return mul print(multiply(1, 2, 3, 4, 5)) #output: 120 **kwargs **kwargs is a special syntax used in the function definition to pass variable-length keyworded arguments. Here, also, “kwargs” is used just by convention. You can use any other name. Keyworded argument means a variable that has a name when passed to a function. It is actually a dictionary of the variable names and its value. def tellArguments(**kwargs): for key, value in kwargs.items(): print(key + ": " + value) tellArguments(arg1 = "argument 1", arg2 = "argument 2", arg3 = "argument 3") #output: # arg1: argument 1 # arg2: argument 2 # arg3: argument 3 38. What are negative indexes and why are they used? Negative indexes are the indexes from the end of the list or tuple or string. Arr[-1] means the last element of array Arr[] arr = [1, 2, 3, 4, 5, 6] #get the last element print(arr[-1]) #output 6 #get the second last element print(arr[-2]) #output 5 Python OOPS Interview Questions 39. How do you create a class in Python? To create a class in Python, we use the keyword “class” as shown in the example below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name To instantiate or create an object from the class created above, we do the following: emp_1=InterviewbitEmployee("Mr. Employee") To access the name attribute, we just call the attribute using the dot operator as shown below: print(emp_1.emp_name) # Prints Mr. Employee To create methods inside the class, we include the methods under the scope of the class as shown below: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) The self parameter in the init and introduce functions represent the reference to the current class instance which is used for accessing attributes and methods of that class. The self parameter has to be the first parameter of any method defined inside the class. The method of the class InterviewbitEmployee can be accessed as shown below: emp_1.introduce() The overall program would look like this: class InterviewbitEmployee: def __init__(self, emp_name): self.emp_name = emp_name def introduce(self): print("Hello I am " + self.emp_name) # create an object of InterviewbitEmployee class emp_1 = InterviewbitEmployee("Mr Employee") print(emp_1.emp_name) #print employee name emp_1.introduce() #introduce the employee logo Practice Problems Solve these problems to ace this concept Classes and Objects Medium 13.56 Mins Solve 40. How does inheritance work in Python? Explain it with an example. Inheritance gives the power to a class to access all attributes and methods of another class. It aids in code reusability and helps the developer to maintain applications without redundant code. The class inheriting from another class is a child class or also called a derived class. The class from which a child class derives the members are called parent class or superclass. Python supports different kinds of inheritance, they are: Single Inheritance: Child class derives members of one parent class. # Parent class class ParentClass: def par_func(self): print("I am parent class function") # Child class class ChildClass(ParentClass): def child_func(self): print("I am child class function") # Driver code obj1 = ChildClass() obj1.par_func() obj1.child_func() Multi-level Inheritance: The members of the parent class, A, are inherited by child class which is then inherited by another child class, B. The features of the base class and the derived class are further inherited into the new derived class, C. Here, A is the grandfather class of class C. # Parent class class A: def __init__(self, a_name): self.a_name = a_name # Intermediate class class B(A): def __init__(self, b_name, a_name): self.b_name = b_name # invoke constructor of class A A.__init__(self, a_name) # Child class class C(B): def __init__(self,c_name, b_name, a_name): self.c_name = c_name # invoke constructor of class B B.__init__(self, b_name, a_name) def display_names(self): print("A name : ", self.a_name) print("B name : ", self.b_name) print("C name : ", self.c_name) # Driver code obj1 = C('child', 'intermediate', 'parent') print(obj1.a_name) obj1.display_names() Multiple Inheritance: This is achieved when one child class derives members from more than one parent class. All features of parent classes are inherited in the child class. # Parent class1 class Parent1: def parent1_func(self): print("Hi I am first Parent") # Parent class2 class Parent2: def parent2_func(self): print("Hi I am second Parent") # Child class class Child(Parent1, Parent2): def child_func(self): self.parent1_func() self.parent2_func() # Driver's code obj1 = Child() obj1.child_func() Hierarchical Inheritance: When a parent class is derived by more than one child class, it is called hierarchical inheritance. # Base class class A: def a_func(self): print("I am from the parent class.") # 1st Derived class class B(A): def b_func(self): print("I am from the first child.") # 2nd Derived class class C(A): def c_func(self): print("I am from the second child.") # Driver's code obj1 = B() obj2 = C() obj1.a_func() obj1.b_func() #child 1 method obj2.a_func() obj2.c_func() #child 2 method 41. How do you access parent members in the child class? Following are the ways using which you can access parent class members within a child class: By using Parent class name: You can use the name of the parent class to access the attributes as shown in the example below: class Parent(object): # Constructor def __init__(self, name): self.name = name class Child(Parent): # Constructor def __init__(self, name, age): Parent.name = name self.age = age def display(self): print(Parent.name, self.age) # Driver Code obj = Child("Interviewbit", 6) obj.display() By using super(): The parent class members can be accessed in child class using the super keyword. class Parent(object): # Constructor def __init__(self, name): self.name = name class Child(Parent): # Constructor def __init__(self, name, age): ''' In Python 3.x, we can also use super().__init__(name) ''' super(Child, self).__init__(name) self.age = age def display(self): # Note that Parent.name cant be used # here since super() is used in the constructor print(self.name, self.age) # Driver Code obj = Child("Interviewbit", 6) obj.display() 42. Are access specifiers used in Python? Python does not make use of access specifiers specifically like private, public, protected, etc. However, it does not derive this from any variables. It has the concept of imitating the behaviour of variables by making use of a single (protected) or double underscore (private) as prefixed to the variable names. By default, the variables without prefixed underscores are public. Example: # to demonstrate access specifiers class InterviewbitEmployee: # protected members _emp_name = None _age = None # private members __branch = None # constructor def __init__(self, emp_name, age, branch): self._emp_name = emp_name self._age = age self.__branch = branch #public member def display(): print(self._emp_name +" "+self._age+" "+self.__branch) 43. Is it possible to call parent class without its instance creation? Yes, it is possible if the base class is instantiated by other child classes or if the base class is a static method. 44. How is an empty class created in Python? An empty class does not have any members defined in it. It is created by using the pass keyword (the pass command does nothing in Python). We can create objects for this class outside the class. For example- class EmptyClassDemo: pass obj=EmptyClassDemo() obj.name="Interviewbit" print("Name created= ",obj.name) Output: Name created = Interviewbit 45. Differentiate between new and override modifiers. The new modifier is used to instruct the compiler to use the new implementation and not the base class function. The Override modifier is useful for overriding a base class function inside the child class. 46. Why is finalize used? Finalize method is used for freeing up the unmanaged resources and clean up before the garbage collection method is invoked. This helps in performing memory management tasks. 47. What is init method in Python? The init method works similarly to the constructors in Java. The method is run as soon as an object is instantiated. It is useful for initializing any attributes or default behaviour of the object at the time of instantiation. For example: class InterviewbitEmployee: # init method / constructor def __init__(self, emp_name): self.emp_name = emp_name # introduce method def introduce(self): print('Hello, I am ', self.emp_name) emp = InterviewbitEmployee('Mr Employee') # __init__ method is called here and initializes the object name with "Mr Employee" emp.introduce() 48. How will you check if a class is a child of another class? This is done by using a method called issubclass() provided by Python. The method tells us if any class is a child of another class by returning true or false accordingly. For example: class Parent(object): pass class Child(Parent): pass # Driver Code print(issubclass(Child, Parent)) #True print(issubclass(Parent, Child)) #False We can check if an object is an instance of a class by making use of isinstance() method: obj1 = Child() obj2 = Parent() print(isinstance(obj2, Child)) #False print(isinstance(obj2, Parent)) #True Python Pandas Interview Questions 49. What do you know about pandas? Pandas is an open-source, Python-based library used in data manipulation applications requiring high performance. The name is derived from “Panel Data” having multidimensional data. This was developed in 2008 by Wes McKinney and was developed for data analysis. Pandas are useful in performing 5 major steps of data analysis - Load the data, clean/manipulate it, prepare it, model it, and analyze the data. 50. Define pandas dataframe. A dataframe is a 2D mutable and tabular structure for representing data labelled with axes - rows and columns. The syntax for creating dataframe: import pandas as pd dataframe = pd.DataFrame( data, index, columns, dtype) where: data - Represents various forms like series, map, ndarray, lists, dict etc. index - Optional argument that represents an index to row labels. columns - Optional argument for column labels. Dtype - the data type of each column. Again optional. 51. How will you combine different pandas dataframes? The dataframes can be combines using the below approaches: append() method: This is used to stack the dataframes horizontally. Syntax: df1.append(df2) concat() method: This is used to stack dataframes vertically. This is best used when the dataframes have the same columns and similar fields. Syntax: pd.concat([df1, df2]) join() method: This is used for extracting data from various dataframes having one or more common columns. df1.join(df2) 52. Can you create a series from the dictionary object in pandas? One dimensional array capable of storing different data types is called a series. We can create pandas series from a dictionary object as shown below: import pandas as pd dict_info = {'key1' : 2.0, 'key2' : 3.1, 'key3' : 2.2} series_obj = pd.Series(dict_info) print (series_obj) Output: x 2.0 y 3.1 z 2.2 dtype: float64 If an index is not specified in the input method, then the keys of the dictionaries are sorted in ascending order for constructing the index. In case the index is passed, then values of the index label will be extracted from the dictionary. 53. How will you identify and deal with missing values in a dataframe? We can identify if a dataframe has missing values by using the isnull() and isna() methods. missing_data_count=df.isnull().sum() We can handle missing values by either replacing the values in the column with 0 as follows: df[‘column_name’].fillna(0) Or by replacing it with the mean value of the column df[‘column_name’] = df[‘column_name’].fillna((df[‘column_name’].mean())) 54. What do you understand by reindexing in pandas? Reindexing is the process of conforming a dataframe to a new index with optional filling logic. If the values are missing in the previous index, then NaN/NA is placed in the location. A new object is returned unless a new index is produced that is equivalent to the current one. The copy value is set to False. This is also used for changing the index of rows and columns in the dataframe. 55. How to add new column to pandas dataframe? A new column can be added to a pandas dataframe as follows: import pandas as pd data_info = {'first' : pd.Series([1, 2, 3], index=['a', 'b', 'c']), 'second' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(data_info) #To add new column third df['third']=pd.Series([10,20,30],index=['a','b','c']) print (df) #To add new column fourth df['fourth']=df['first']+info['third'] print (df) 56. How will you delete indices, rows and columns from a dataframe? To delete an Index: Execute del df.index.name for removing the index by name. Alternatively, the df.index.name can be assigned to None. For example, if you have the below dataframe: Column 1 Names John 1 Jack 2 Judy 3 Jim 4 To drop the index name “Names”: df.index.name = None # Or run the below: # del df.index.name print(df) Column 1 John 1 Jack 2 Judy 3 Jim 4 To delete row/column from dataframe: drop() method is used to delete row/column from dataframe. The axis argument is passed to the drop method where if the value is 0, it indicates to drop/delete a row and if 1 it has to drop the column. Additionally, we can try to delete the rows/columns in place by setting the value of inplace to True. This makes sure that the job is done without the need for reassignment. The duplicate values from the row/column can be deleted by using the drop_duplicates() method. 57. Can you get items of series A that are not available in another series B? This can be achieved by using the ~ (not/negation symbol) and isin() method as shown below. import pandas as pd df1 = pd.Series([2, 4, 8, 10, 12]) df2 = pd.Series([8, 12, 10, 15, 16]) df1=df1[~df1.isin(df2)] print(df1) """ Output: 0 2 1 4 dtype: int64 """ 58. How will you get the items that are not common to both the given series A and B? We can achieve this by first performing the union of both series, then taking the intersection of both series. Then we follow the approach of getting items of union that are not there in the list of the intersection. The following code demonstrates this: import pandas as pd import numpy as np df1 = pd.Series([2, 4, 5, 8, 10]) df2 = pd.Series([8, 10, 13, 15, 17]) p_union = pd.Series(np.union1d(df1, df2)) # union of series p_intersect = pd.Series(np.intersect1d(df1, df2)) # intersection of series unique_elements = p_union[~p_union.isin(p_intersect)] print(unique_elements) """ Output: 0 2 1 4 2 5 5 13 6 15 7 17 dtype: int64 """ 59. While importing data from different sources, can the pandas library recognize dates? Yes, they can, but with some bit of help. We need to add the parse_dates argument while we are reading data from the sources. Consider an example where we read data from a CSV file, we may encounter different date-time formats that are not readable by the pandas library. In this case, pandas provide flexibility to build our custom date parser with the help of lambda functions as shown below: import pandas as pd from datetime import datetime dateparser = lambda date_val: datetime.strptime(date_val, '%Y-%m-%d %H:%M:%S') df = pd.read_csv("some_file.csv", parse_dates=['datetime_column'], date_parser=dateparser) Numpy Interview Questions 60. What do you understand by NumPy? NumPy is one of the most popular, easy-to-use, versatile, open-source, Python-based, general-purpose package that is used for processing arrays. NumPy is short for NUMerical Python. This is very famous for its highly optimized tools that result in high performance and powerful N-Dimensional array processing feature that is designed explicitly to work on complex arrays. Due to its popularity and powerful performance and its flexibility to perform various operations like trigonometric operations, algebraic and statistical computations, it is most commonly used in performing scientific computations and various broadcasting functions. The following image shows the applications of NumPy: 61. How are NumPy arrays advantageous over Python lists? The list data structure of Python is very highly efficient and is capable of performing various functions. But, they have severe limitations when it comes to the computation of vectorized operations which deals with element-wise multiplication and addition. The Python lists also require the information regarding the type of every element which results in overhead as type dispatching code gets executes every time any operation is performed on any element. This is where the NumPy arrays come into the picture as all the limitations of Python lists are handled in NumPy arrays. Additionally, as the size of the NumPy arrays increases, NumPy becomes around 30x times faster than the Python List. This is because the Numpy arrays are densely packed in the memory due to their homogenous nature. This ensures the memory free up is also faster. logo Practice Problems Solve these problems to ace this concept Numpy Arrays Easy 12.31 Mins Solve 62. What are the steps to create 1D, 2D and 3D arrays? 1D array creation: import numpy as np one_dimensional_list = [1,2,4] one_dimensional_arr = np.array(one_dimensional_list) print("1D array is : ",one_dimensional_arr) 2D array creation: import numpy as np two_dimensional_list=[[1,2,3],[4,5,6]] two_dimensional_arr = np.array(two_dimensional_list) print("2D array is : ",two_dimensional_arr) 3D array creation: import numpy as np three_dimensional_list=[[[1,2,3],[4,5,6],[7,8,9]]] three_dimensional_arr = np.array(three_dimensional_list) print("3D array is : ",three_dimensional_arr) ND array creation: This can be achieved by giving the ndmin attribute. The below example demonstrates the creation of a 6D array: import numpy as np ndArray = np.array([1, 2, 3, 4], ndmin=6) print(ndArray) print('Dimensions of array:', ndArray.ndim) 63. You are given a numpy array and a new column as inputs. How will you delete the second column and replace the column with a new column value? Example: Given array: [[35 53 63] [72 12 22] [43 84 56]] New Column values: [ 20 30 40 ] Solution: import numpy as np #inputs inputArray = np.array([[35,53,63],[72,12,22],[43,84,56]]) new_col = np.array([[20,30,40]]) # delete 2nd column arr = np.delete(inputArray , 1, axis = 1) #insert new_col to array arr = np.insert(arr , 1, new_col, axis = 1) print (arr) 64. How will you efficiently load data from a text file? We can use the method numpy.loadtxt() which can automatically read the file’s header and footer lines and the comments if any. This method is highly efficient and even if this method feels less efficient, then the data should be represented in a more efficient format such as CSV etc. Various alternatives can be considered depending on the version of NumPy used. Following are the file formats that are supported: Text files: These files are generally very slow, huge but portable and are human-readable. Raw binary: This file does not have any metadata and is not portable. But they are fast. Pickle: These are borderline slow and portable but depends on the NumPy versions. HDF5: This is known as the High-Powered Kitchen Sink format which supports both PyTables and h5py format. .npy: This is NumPy's native binary data format which is extremely simple, efficient and portable. 65. How will you read CSV data into an array in NumPy? This can be achieved by using the genfromtxt() method by setting the delimiter as a comma. from numpy import genfromtxt csv_data = genfromtxt('sample_file.csv', delimiter=',') 66. How will you sort the array based on the Nth column? For example, consider an array arr. arr = np.array([[8, 3, 2], [3, 6, 5], [6, 1, 4]]) Let us try to sort the rows by the 2nd column so that we get: [[6, 1, 4], [8, 3, 2], [3, 6, 5]] We can do this by using the sort() method in numpy as: import numpy as np arr = np.array([[8, 3, 2], [3, 6, 5], [6, 1, 4]]) #sort the array using np.sort arr = np.sort(arr.view('i8,i8,i8'), order=['f1'], axis=0).view(np.int) We can also perform sorting and that too inplace sorting by doing: arr.view('i8,i8,i8').sort(order=['f1'], axis=0) 67. How will you find the nearest value in a given numpy array? We can use the argmin() method of numpy as shown below: import numpy as np def find_nearest_value(arr, value): arr = np.asarray(arr) idx = (np.abs(arr - value)).argmin() return arr[idx] #Driver code arr = np.array([ 0.21169, 0.61391, 0.6341, 0.0131, 0.16541, 0.5645, 0.5742]) value = 0.52 print(find_nearest_value(arr, value)) # Prints 0.5645 68. How will you reverse the numpy array using one line of code? This can be done as shown in the following: reversed_array = arr[::-1] where arr = original given array, reverse_array is the resultant after reversing all elements in the input. 69. How will you find the shape of any given NumPy array? We can use the shape attribute of the numpy array to find the shape. It returns the shape of the array in terms of row count and column count of the array. import numpy as np arr_two_dim = np.array([("x1","x2", "x3","x4"), ("x5","x6", "x7","x8" )]) arr_one_dim = np.array([3,2,4,5,6]) # find and print shape print("2-D Array Shape: ", arr_two_dim.shape) print("1-D Array Shape: ", arr_one_dim.shape) """ Output: 2-D Array Shape: (2, 4) 1-D Array Shape: (5,) """ Python Libraries Interview Questions 70. Differentiate between a package and a module in Python. The module is a single Python file. A module can import other modules (other Python files) as objects. Whereas, a package is the folder/directory where different sub-packages and the modules reside. A Python module is created by saving a file with the extension of .py. This file will have classes and functions that are reusable in the code as well as across modules. A Python package is created by following the below steps: Create a directory and give a valid name that represents its operation. Place modules of one kind in this directory. Create __init__.py file in this directory. This lets Python know the directory we created is a package. The contents of this package can be imported across different modules in other packages to reuse the functionality. 71. What are some of the most commonly used built-in modules in Python? Python modules are the files having Python code which can be functions, variables or classes. These go by .py extension. The most commonly available built-in modules are: os math sys random re datetime JSON 72. What are lambda functions? Lambda functions are generally inline, anonymous functions represented by a single expression. They are used for creating function objects during runtime. They can accept any number of parameters. They are usually used where functions are required only for a short period. They can be used as: mul_func = lambda x,y : x*y print(mul_func(6, 4)) # Output: 24 73. How can you generate random numbers? Python provides a module called random using which we can generate random numbers. We have to import a random module and call the random() method as shown below: The random() method generates float values lying between 0 and 1 randomly. import random print(random.random()) To generate customised random numbers between specified ranges, we can use the randrange() method Syntax: randrange(beginning, end, step) For example: import random print(random.randrange(5,100,2)) 74. Can you easily check if all characters in the given string is alphanumeric? This can be easily done by making use of the isalnum() method that returns true in case the string has only alphanumeric characters. For Example - "abdc1321".isalnum() #Output: True "xyz@123$".isalnum() #Output: False Another way is to use match() method from the re (regex) module as shown: import re print(bool(re.match('[A-Za-z0-9]+$','abdc1321'))) # Output: True print(bool(re.match('[A-Za-z0-9]+$','xyz@123$'))) # Output: False 75. What are the differences between pickling and unpickling? Pickling is the conversion of Python objects to binary form. Whereas, unpickling is the conversion of binary form data to Python objects. The pickled objects are used for storing in disks or external memory locations. Unpickled objects are used for getting the data back as Python objects upon which processing can be done in Python. Python provides a pickle module for achieving this. Pickling uses the pickle.dump() method to dump Python objects into disks. Unpickling uses the pickle.load() method to get back the data as Python objects. 77. Define PythonPATH. It is an environment variable used for incorporating additional directories during the import of a module or a package. PythonPATH is used for checking if the imported packages or modules are available in the existing directories. Not just that, the interpreter uses this environment variable to identify which module needs to be loaded. 78. Define PIP. PIP stands for Python Installer Package. As the name indicates, it is used for installing different Python modules. It is a command-line tool providing a seamless interface for installing different Python modules. It searches over the internet for the package and installs them into the working directory without the need for any interaction with the user. The syntax for this is: pip install <package_name> 79. Are there any tools for identifying bugs and performing static analysis in Python? Yes, there are tools like PyChecker and Pylint which are used as static analysis and linting tools respectively. PyChecker helps find bugs in Python source code files and raises alerts for code issues and their complexity. Pylint checks for the module’s coding standards and supports different plugins to enable custom features to meet this requirement. 80. Differentiate between deep and shallow copies. Shallow copy does the task of creating new objects storing references of original elements. This does not undergo recursion to create copies of nested objects. It just copies the reference details of nested objects. Deep copy creates an independent and new copy of an object and even copies all the nested objects of the original element recursively. 81. What is main function in Python? How do you invoke it? In the world of programming languages, the main is considered as an entry point of execution for a program. But in Python, it is known that the interpreter serially interprets the file line-by-line. This means that Python does not provide main() function explicitly. But this doesn't mean that we cannot simulate the execution of main. This can be done by defining user-defined main() function and by using the __name__ property of Python file. This __name__ variable is a special built-in variable that points to the name of the current module. This can be done as shown below: def main(): print("Hi Interviewbit!") if __name__=="__main__": main() Python Programming Examples 82. Write Python function which takes a variable number of arguments. A function that takes variable arguments is called a function prototype. Syntax: def function_name(*arg_list) For example: def func(*var): for i in var: print(i) func(1) func(20,1,6) The * in the function argument represents variable arguments in the function. 83. Write a program which takes a sequence of numbers and check if all numbers are unique. You can do this by converting the list to set by using set() method and comparing the length of this set with the length of the original list. If found equal, return True. def check_distinct(data_list): if len(data_list) == len(set(data_list)): return True else: return False; print(check_distinct([1,6,5,8])) #Prints True print(check_distinct([2,2,5,5,7,8])) #Prints False 84. Write a program for counting the number of every character of a given text file. The idea is to use collections and pprint module as shown below: import collections import pprint with open("sample_file.txt", 'r') as data: count_data = collections.Counter(data.read().upper()) count_value = pprint.pformat(count_data) print(count_value) 85. Write a program to check and return the pairs of a given array A whose sum value is equal to a target value N. This can be done easily by using the phenomenon of hashing. We can use a hash map to check for the current value of the array, x. If the map has the value of (N-x), then there is our pair. def print_pairs(arr, N): # hash set hash_set = set() for i in range(0, len(arr)): val = N-arr[i] if (val in hash_set): #check if N-x is there in set, print the pair print("Pairs " + str(arr[i]) + ", " + str(val)) hash_set.add(arr[i]) # driver code arr = [1, 2, 40, 3, 9, 4] N = 3 print_pairs(arr, N) 86. Write a Program to add two integers >0 without using the plus operator. We can use bitwise operators to achieve this. def add_nums(num1, num2): while num2 != 0: data = num1 & num2 num1 = num1 ^ num2 num2 = data << 1 return num1 print(add_nums(2, 10)) 87. Write a Program to solve the given equation assuming that a,b,c,m,n,o are constants: ax + by = c mx + ny = o By solving the equation, we get: a, b, c, m, n, o = 5, 9, 4, 7, 9, 4 temp = a*n - b*m if n != 0: x = (c*n - b*o) / temp y = (a*o - m*c) / temp print(str(x), str(y)) 88. Write a Program to match a string that has the letter ‘a’ followed by 4 to 8 'b’s. We can use the re module of Python to perform regex pattern comparison here. import re def match_text(txt_data): pattern = 'ab{4,8}' if re.search(pattern, txt_data): #search for pattern in txt_data return 'Match found' else: return('Match not found') print(match_text("abc")) #prints Match not found print(match_text("aabbbbbc")) #prints Match found 89. Write a Program to convert date from yyyy-mm-dd format to dd-mm-yyyy format. We can again use the re module to convert the date string as shown below: import re def transform_date_format(date): return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\\3-\\2-\\1', date) date_input = "2021-08-01" print(transform_date_format(date_input)) You can also use the datetime module as shown below: from datetime import datetime new_date = datetime.strptime("2021-08-01", "%Y-%m-%d").strftime("%d:%m:%Y") print(new_data) 90. Write a Program to combine two different dictionaries. While combining, if you find the same keys, you can add the values of these same keys. Output the new dictionary We can use the Counter method from the collections module from collections import Counter d1 = {'key1': 50, 'key2': 100, 'key3':200} d2 = {'key1': 200, 'key2': 100, 'key4':300} new_dict = Counter(d1) + Counter(d2) print(new_dict) 91. How will you access the dataset of a publicly shared spreadsheet in CSV format stored in Google Drive? We can use the StringIO module from the io module to read from the Google Drive link and then we can use the pandas library using the obtained data source. from io import StringIO import pandas csv_link = "https://docs.google.com/spreadsheets/d/..." data_source = StringIO.StringIO(requests.get(csv_link).content)) dataframe = pd.read_csv(data_source) print(dataframe.head())