Understanding Python Lists
Python lists are one of the most fundamental and versatile data structures in the Python programming language. A list is an ordered collection of items, which can be of different data types, such as integers, floats, strings, or even other lists.
Lists are defined using square brackets []
, and the individual elements are separated by commas. For example, [1, 2, 3, 'LabEx', 3.14]
is a valid Python list.
Some key characteristics of Python lists:
List Indexing and Slicing
Lists are zero-indexed, meaning the first element has an index of 0, the second element has an index of 1, and so on. You can access individual elements using their index, like this:
my_list = [1, 2, 3, 'LabEx', 3.14]
print(my_list[0]) ## Output: 1
print(my_list[3]) ## Output: 'LabEx'
You can also use slicing to extract a subset of the list:
my_list = [1, 2, 3, 'LabEx', 3.14]
print(my_list[1:4]) ## Output: [2, 3, 'LabEx']
List Operations
Python lists support a variety of operations, such as concatenation, repetition, and membership testing:
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']
print(list1 + list2) ## Output: [1, 2, 3, 'a', 'b', 'c']
print(list1 * 2) ## Output: [1, 2, 3, 1, 2, 3]
print(3 in list1) ## Output: True
List Methods
Python lists come with a set of built-in methods that allow you to manipulate and operate on the list. Some common methods include append()
, insert()
, remove()
, pop()
, and sort()
.
my_list = [1, 2, 3]
my_list.append(4) ## my_list is now [1, 2, 3, 4]
my_list.insert(1, 'LabEx') ## my_list is now [1, 'LabEx', 2, 3, 4]
my_list.remove(3) ## my_list is now [1, 'LabEx', 2, 4]
popped_item = my_list.pop() ## popped_item is 4, my_list is now [1, 'LabEx', 2]
my_list.sort() ## my_list is now [1, 2, 'LabEx']
Understanding the basics of Python lists is essential for working with and manipulating data in your Python programs. In the next section, we'll explore how to combine multiple Python lists into one.