In Python, List is a versatile and commonly used data structure that stores a collection of elements.
Lists are mutable, meaning their elements can be changed after creation.
They can hold elements of different data types, and the elements can be accessed using their indices.
Lists are quite similar to arrays from other programming languages, such as Array in Javascript and Array List in Java.
Here's how to work with lists in Python:
# comma separated value inside [] brackets. list_name = [value1, value2]
We can create a list by enclosing elements within square brackets [], separated by commas.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(your_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9] print(type(your_list)) # Output: <class 'list'>
We can access elements of a list using their indices. Indexing starts from 0 for the first element and goes up to "len(your_list) - 1" for the last element.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(your_list[0]) # Output: 1 print(your_list[6]) # Output: 7
We can extract a subset of elements from a list using slicing.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(your_list[3:6]) # Output: [4, 5, 6]
We can modify elements of a list by assigning new values to their indices.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] your_list[7] = 10 print(your_list) # Output: [1, 2, 3, 4, 5, 6, 7, 10, 9]
We can add elements to a list using the "append()" method to add a single element or using the "extend()" method to add multiple elements from another list.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] your_list.append(10) print(your_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] new_elements = [11, 12, 13] your_list.extend(new_elements) print(your_list) # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
We can remove elements from a list using the "remove()" method to remove a specific element, or using the "pop()" method to remove an element by index.
your_list = [1, 2, 3, 4, 5, 6, 7, 8, 9] your_list.remove(8) print(your_list) # Output: [1, 2, 3, 4, 5, 6, 7, 9] removed_element = your_list.pop(4) print(your_list) # Output: [1, 2, 3, 4, 6, 7, 9] print(removed_element) # Output: 5
List comprehensions provide a concise way to create lists.
squares = [x**2 for x in range(1, 8)] print(squares) # Output: [1, 4, 9, 16, 25, 36, 49]
The "for" loop is used to iterate over elements of a sequence (such as a list, tuple, string, or range) or any iterable object.
It allows us to execute a block of code repeatedly for each item in the sequence.
for item in sequence: # code block to be executed for each item
"item" is a variable that represents each item in the sequence.
"sequence" is the iterable object over which you want to iterate.
We can use a for loop to iterate over elements of a list.
fruits = ["apple", "banana", "orange"] for fruit in fruits: print(fruit) # Output: apple, banana, orange