-
Hajipur, Bihar, 844101
A list in Python is used to store multiple values in a single variable.
Lists are ordered, changeable, and allow duplicate values.
fruits = ["apple", "banana", "cherry"]
print(fruits)
print(fruits[0]) # apple
print(fruits[1]) # banana
print(fruits[-1]) # cherry
print(fruits[1:3]) # ['banana', 'cherry']
print(fruits[:2]) # ['apple', 'banana']
fruits[1] = "orange"
print(fruits) # ['apple', 'orange', 'cherry']
for fruit in fruits:
print(fruit)
if "banana" in fruits:
print("Yes")
print(len(fruits)) # 3
fruits.append("mango") # add to end
fruits.insert(1, "grape") # insert at position 1
fruits.remove("banana") # remove by value
fruits.pop() # remove last item
del fruits[0] # remove by index
new_list = fruits.copy()
list1 = ["a", "b"]
list2 = [1, 2]
list3 = list1 + list2
Practice adding, removing, looping, slicing, and checking items in lists.
Q1. Write a Python program to create a list of 5 countries and print them.
Q2. Write a Python program to print the second and last items in a list.
Q3. Write a Python program to change the third item of a list to "India"
.
Q4. Write a Python program to add "Python"
to the end of a list using append()
.
Q5. Write a Python program to insert "Java"
at index 2 of a list.
Q6. Write a Python program to remove "C++"
from a list using remove()
.
Q7. Write a Python program to copy one list into another using the copy()
method.
Q8. Write a Python program to check if "HTML"
exists in a list using the in
keyword.
Q9. Write a Python program to print all items in a list using a loop.
Q10. Write a Python program to join two lists: one with strings and one with numbers, and print the result.
Q1: What is a list in Python?
Q2: What is the index of the first item in a list?
Q3: Which method adds an item to the end of a list?
Q4: What does pop() do?
Q5: How do you get the number of items in a list?
Q6: Which method creates a full copy of a list?
Q7: What will fruits[-1] return?
Q8: What does del fruits[0] do?
Q9: Can lists contain mixed data types?
Q10: Which of the following joins two lists?