Python Lists and List comprehension
Understanding Lists, List comprehension, Manipulating Elements, and Performing Common Operations
Website Visitors:Lists in Python
In Python, a list is an ordered collection of items, where each item can be of any data type. Lists are mutable, which means you can modify their contents. They are defined by enclosing the items in square brackets [ ]
and separating them with commas. Here are some examples and detailed explanations of working with Python lists:
-
Creating a List:
1
fruits = ['apple', 'banana', 'cherry']
In this example, we created a list called
fruits
with three items:'apple'
,'banana'
, and'cherry'
. -
Accessing Elements:
1
print(fruits[0]) # Output: 'apple'
Lists are zero-indexed, so you can access individual elements using their index. In this case,
fruits[0]
returns the first element'apple'
. -
Modifying Elements:
1 2
fruits[1] = 'orange' print(fruits) # Output: ['apple', 'orange', 'cherry']
Lists are mutable, so you can change the value of an element by assigning a new value to its index.
-
List Length:
1
print(len(fruits)) # Output: 3
The
len()
function returns the number of elements in a list. -
Appending Elements:
1 2
fruits.append('grape') print(fruits) # Output: ['apple', 'orange', 'cherry', 'grape']
The
append()
method adds an item to the end of the list. When you append an item to the list, it will always add at the end of the list. You can start always start an empty list and append elements later on. -
Inserting Elements:
1 2
fruits.insert(1, 'pear') print(fruits) # Output: ['apple', 'pear', 'orange', 'cherry', 'grape']
The
insert()
method inserts an item at a specified index, pushing the existing items to the right. If you insert an element at a position higher than the number of elements in the list, it will be added at the end. For example, if you have 5 elements in the list, and you insert a new element at 27th position like fruits.insert(27,‘banana’), it will be inserted at the end of the list. -
Removing Elements:
1 2
fruits.remove('orange') print(fruits) # Output: ['apple', 'pear', 'cherry', 'grape']
The
remove()
method removes the first occurrence of a specified item from the list. -
The
pop()
method is used to remove and return an element from a specific index in a list. Here’s how it works:1 2 3 4 5
fruits = ['apple', 'banana', 'cherry', 'orange'] removed_fruit = fruits.pop(1) print(removed_fruit) # Output: 'banana' print(fruits) # Output: ['apple', 'cherry', 'orange']
In the above example,
pop(1)
removes the element at index 1 (which is'banana'
) from thefruits
list and returns it. The list is then modified, containing the remaining elements['apple', 'cherry', 'orange']
.If you don’t provide an index to the
pop()
method, it will remove and return the last element of the list by default. Here’s an example:1 2 3 4 5
fruits = ['apple', 'banana', 'cherry', 'orange'] removed_fruit = fruits.pop() print(removed_fruit) # Output: 'orange' print(fruits) # Output: ['apple', 'banana', 'cherry']
In this case,
pop()
removes and returns the last element'orange'
, leaving the list with['apple', 'banana', 'cherry']
.The
pop()
method is useful when you want to remove an element from a list at a specific index and also capture the value of the removed element. It allows you to modify the list in-place and obtain the removed item for further use or processing. -
Slicing a List:
1
print(fruits[1:3]) # Output: ['pear', 'cherry']
You can extract a sublist from a list using slicing. The start index is inclusive, and the end index is exclusive.
-
Iterating over a List:
1 2
for fruit in fruits: print(fruit)
You can use a
for
loop to iterate over the elements of a list. -
List Concatenation:
1 2 3
more_fruits = ['kiwi', 'melon'] all_fruits = fruits + more_fruits print(all_fruits) # Output: ['apple', 'pear', 'cherry', 'grape', 'kiwi', 'melon']
You can concatenate two lists using the
+
operator. -
Search for items lin list: You can search for items in a list as shown below. Note that items in the list are case sensitive.
1 2 3 4 5 6
x = ["This","is",'A',"list"] 'A' in x # Output True 'a' in x # Output False 'This' in x # Output True 'THIS' in x # Output False
-
Iterating over lists:
1 2 3 4 5 6
animals = ["Lion", "Zebra", "Dolphin", "Monkey"] chars = 0 for animal in animals: chars += len(animal) print("Total characters: {}, Average length: {}".format(chars, chars/len(animals)))python
1 2 3 4 5 6 7
winners = ["Ashley", "Dylan", "Reese"] for index, person in enumerate(winners): print("{} - {}".format(index + 1, person)) #Output 1 - Ashley 2 - Dylan 3 - Reese
The enumerate() function takes a list as a parameter and returns a tuple for each element in the list. The first value of the tuple is the index and the second value is the element itself.
The
enumerate
function is used to loop over the list and have an automatic counter/index along with it. Theindex
variable will take on the value of the counter, and theperson
variable will take on the value of the current element in the list.1 2 3 4 5 6
def full_emails(people): result = [] for email, name in people: result.append("{} <{}>".format(name, email)) return result print(full_emails([("alex@example.com", "Alex Diego"), ("shay@example.com", "Shay Brandt")]))
-
Returning multiple values from functions
One of the most useful aspects of tuples in Python is their ability to return multiple values from a function. This allows a function to produce more than one result, providing flexibility and improving code readability.
Here’s an example:
1 2 3 4 5
def calculate_numbers(a, b): return a+b, a-b, a*b, a/b result = calculate_numbers(10, 2) print(result) # Outputs: (12, 8, 20, 5.0)
In the above function, the four arithmetic calculations are returned as a tuple, which can be assigned to a single variable (result), or “unpacked” into multiple variables:
1 2 3 4 5 6
def calculate_numbers(a, b): return a+b, a-b, a*b, a/b add_result, sub_result, mul_result, div_result = calculate_numbers(10, 2) print(add_result) # Outputs: 12 print(sub_result) # Outputs: 8
-
Sorting in Lists: When you use .sort() it changes the list. so no matter how many times you print you ll get [1, 2, 4, 6, 7] in output.
1 2 3
numbers = [ 4, 6, 2, 7, 1 ] numbers.sort() print(numbers)
If you use sorted(numbers) it just changes the values for the output only but the actual values are not changed.
|
|
If you want to use a custom value to sort the values like length of the characters etc, then you should use the key
parameter.
|
|
Lists and tuples are both sequences and they share a number of sequence operations. The following common sequence operations are used by both lists and tuples:
-
len(sequence) - Returns the length of the sequence.
-
for element in sequence - Iterates over each element in the sequence.
-
if element in sequence - Checks whether the element is part of the sequence.
-
sequence - Accesses the element at index of the sequence, starting at zero
-
sequence[x:y] - Accesses a slice starting at index , ending at index [y-1]. If is omitted, the index will start at 0 by default. If [y] is omitted, the len(sequence) will set the ending index position by default.
-
for index, element in enumerate(sequence) - Iterates over both the indices and the elements in the sequence at the same time.
List-specific operations and methods
One major difference between lists and tuples is that lists are mutable (changeable) and tuples are immutable (not changeable). There are a few operations and methods that are specific to changing data within lists:
-
list[index] = x - Replaces the element at index [n] with x.
-
list.append(x) - Appends x to the end of the list.
-
list.insert(index, x) - Inserts x at index position [index].
-
list.pop(index) - Returns the element at [index] and removes it from the list. If [index] position is not in the list, the last element in the list is returned and removed.
-
list.remove(x) - Removes the first occurrence of x in the list.
-
list.sort() - Sorts the items in the list.
-
list.reverse() - Reverses the order of items of the list.
-
list.clear() - Deletes all items in the list.
-
list.copy() - Creates a copy of the list.
-
list.extend(other_list) - Appends all the elements of other_list at the end of list
-
map(function, iterable) - Applies a given function to each item of an iterable (such as a list) and returns a map object with the results
-
zip(*iterables) - Takes in iterables as arguments and returns an iterator that generates tuples, where the i-th tuple contains the i-th element from each of the argument iterables.
These are some common operations you can perform with Python lists. Remember that lists can contain items of any data type, including other lists, making them a versatile tool for storing and manipulating collections of data.
Python list
List Methods:
Python provides several built-in methods to manipulate lists. Some common methods include:
append()
: Adds an element to the end of the list.insert()
: Inserts an element at a specified position. If you enter a number more than the number of items in the list, the element will be added at the end of the list.remove()
: Removes the first occurrence of a specified value.pop()
: Removes and returns the element at a specified index.sort()
: Sorts the list in ascending order.reverse()
: Reverses the order of elements in the list.
List comprehension
Python list comprehension is a concise way to create lists based on existing lists or other iterable objects. It allows you to define a new list with a specific format or condition, all in a single line of code. List comprehensions are often used as a more readable and efficient alternative to traditional loops.
List comprehensions allow us to create new lists based on sequences or ranges. It is basically a shorthand way of creating a new list based on an existing list.
For loop iterates over a sequence of values.
There are no standards or best practices on when to use for loop and list comprehensions. But in general, for complex code, use for loop. For simple or small code, use list comprehension. Use which one makes your code more clear.
The general syntax of a list comprehension is as follows:
|
|
Here’s a breakdown of the components:
-
expression
: This is the value or transformation applied to each item in the iterable. It defines how the new elements in the list are generated. -
item
: It represents an element from the iterable object being iterated over. -
iterable
: It can be a list, tuple, string, or any other iterable object that provides elements to iterate over. -
if condition
(optional): This part allows you to specify an optional condition or filter that determines whether an element should be included in the new list.
Now, let’s see some examples of Python list comprehensions:
-
Creating a list of squares of numbers from 1 to 5:
1 2 3
squares = [x**2 for x in range(1, 6)] print(squares) # Output: [1, 4, 9, 16, 25]
-
Filtering even numbers from a list:
1 2 3 4 5
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] even_numbers = [x for x in numbers if x % 2 == 0] print(even_numbers) # or use the comprehension directly in print statement like, print([x for x in range(1,100) if x%3==0]) # Output: [2, 4, 6, 8, 10]
-
Converting strings to uppercase:
1 2 3 4
words = ["hello", "world", "python"] upper_words = [word.upper() for word in words] print(upper_words) # Output: ['HELLO', 'WORLD', 'PYTHON']
-
Generating a list of tuples from two separate lists:
1 2 3 4 5
names = ["Alice", "Bob", "Charlie"] ages = [25, 30, 35] person_list = [(name, age) for name, age in zip(names, ages)] print(person_list) # Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]
-
print numbers from 1 to 100 which are multiplied by 3.
1 2
z = [x for x in range(0,101) if x % 3 == 0] print(z)
-
print numbers if divisible by 10
1 2 3 4 5 6 7 8 9 10 11 12 13
print("List comprehension result:") print([x for x in range(1,101) if x % 10 == 0]) # The list comprehension above accomplishes the same result as # the long form version of the code: print("Long form code result:") my_list = [] for x in range(1,101): if x % 10 == 0: my_list.append(x) print(my_list) # Select Run to observe the two results.
-
print squares of numbers
1 2 3 4 5 6
def squares(start, end): return [n*n for n in range(start, end+1)] print(squares(2, 3)) # Should print [4, 9] print(squares(1, 5)) # Should print [1, 4, 9, 16, 25] print(squares(0, 10)) # Should print [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
-
rename files with extension hpp and rename the extension as h
|
|
List comprehensions can be a powerful tool for concise and expressive list manipulation. They help simplify the code and make it more readable. However, it’s important to use them judiciously, as overly complex or nested list comprehensions may sacrifice readability.
Nested Lists:
Lists can also contain other lists, creating nested lists. This is useful for representing multi-dimensional data structures. Here’s an example of a nested list:
|
|
List Operations:
Python supports various operations on lists, such as concatenation and repetition. Here are some examples:
|
|
Conclusion
Lists are a powerful and flexible data structure in Python that allow you to store and manipulate collections of items efficiently. By understanding the various operations, methods, and features of lists, you can leverage them effectively in your Python programs.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.