A list is one of the most commonly used data structures in Python. A list is used to store multiple values in a single variable.
Lists are ordered, changeable (mutable), and allow duplicate values.
A list is a collection of multiple items stored in a single variable.
students = ["Amit", "Rahul", "Priya"]
print(students)
A list is created using square brackets.
numbers = [10, 20, 30, 40, 50]
print(numbers)
A Python list can contain different types of values.
data = [10, "Python", 25.5, True]
print(data)
Lists allow duplicate values.
numbers = [10, 20, 10, 30, 20]
print(numbers)
List elements are accessed using their index. Python list indexing starts from 0.
names = ["Amit", "Rahul", "Priya"]
print(names[0])
print(names[1])
print(names[2])
Python also supports negative indexing. The last element has index -1.
names = ["Amit", "Rahul", "Priya"]
print(names[-1])
print(names[-2])
Lists are mutable, which means their elements can be changed after the list is created.
names = ["Amit", "Rahul", "Priya"]
names[1] = "Ravi"
print(names)
The len() function returns the number of elements in a list.
numbers = [10, 20, 30, 40]
print(len(numbers))
The in operator checks whether an item exists in a list.
names = ["Amit", "Rahul", "Priya"]
print("Rahul" in names)
print("Ravi" in names)
numbers = [10, 20, 30]
print(50 not in numbers)
Slicing is used to get a portion of a list.
numbers = [10, 20, 30, 40, 50]
print(numbers[1:4])
The start index is included and the stop index is excluded.
numbers = [10, 20, 30, 40, 50]
print(numbers[:3])
numbers = [10, 20, 30, 40, 50]
print(numbers[2:])
numbers = [10, 20, 30, 40, 50]
print(numbers[-3:])
names = ["Amit", "Rahul", "Priya"]
for name in names:
print(name)
numbers = [10, 20, 30]
i = 0
while i < len(numbers):
print(numbers[i])
i += 1
A list can contain other lists. This is called a nested list.
students = [
["Amit", 20],
["Rahul", 21],
["Priya", 19]
]
print(students)
students = [
["Amit", 20],
["Rahul", 21]
]
print(students[0][0])
print(students[1][1])
The + operator can be used to combine two lists.
list1 = [10, 20]
list2 = [30, 40]
result = list1 + list2
print(result)
The * operator can repeat the elements of a list.
numbers = [1, 2]
print(numbers * 3)
The copy() method can be used to create a shallow copy of a list.
numbers = [10, 20, 30]
new_numbers = numbers.copy()
print(new_numbers)
Simply assigning one list to another does not create an independent copy.
list1 = [10, 20, 30]
list2 = list1
list2[0] = 100
print(list1)
Both variables refer to the same list object.
The list() constructor can be used to create a list from another iterable.
text = "Python"
letters = list(text)
print(letters)
List elements can be assigned to multiple variables.
student = ["Rahul", 20, "Python"]
name, age, course = student
print(name)
print(age)
print(course)
Question: Which brackets are used to create a list in Python?