In Python, a list is a mutable, ordered collection of items. Lists can hold a variety of data types (including other lists) and allow for easy manipulation and access to their elements.
Python knows a number of compound data types, used to group other values. The most versatile is the list, which can be written as a list of comma-separated values (items) between square brackets.
Creating a List
You can create a list by placing items inside square brackets [], separated by commas.
# Empty list
empty_list = []
# List of integers
numbers_list = [1, 2, 3, 4, 5]
# List of mixed data types
mixed_list = [1, "Hello", 3.14, True]
Accessing List Elements
You can access elements in a list using indexing. Python uses zero-based indexing, so the first element has an index of 0.
numbers = [20, 30, 40, 50]
print(numbers[0]) # Output: 20
print(numbers[2]) # Output: 40
# Negative indexing accesses elements from the end of the list
print(numbers[-1]) # Output: 50 (last element)
Modifying a List
Since lists are mutable, you can modify, add, or remove elements after the list is created.
Changing elements:
numbers[1] = 35
print(numbers) # Output: [20, 35, 40, 50]
Python List – Interview Questions
Q 1: What is a list in Python?
Q 2: How do you create a list?
Q 3: Are lists mutable in Python?
Q 4: Can a list contain duplicate elements?
Q 5: How do you find the length of a list?
Python List – Objective Questions (MCQs)
Q1. Which of the following correctly creates a list in Python?
Q2. What is the output of the following code?
fruits = ['apple', 'banana', 'cherry']
print(fruits[1])
Q3. Which of the following methods is used to add an element at the end of a list?
Q4. What will be the output of the following code?
numbers = [1, 2, 3]
numbers.append([4, 5])
print(numbers)
Q5. Which of the following statements is true about lists in Python?