😸List

Python offers several built-in data structures to hold and manipulate data efficiently. One such data structure is a list, which is a collection of items stored in a specific order. A list is mutable, which means it can be changed after it is created.

In Python, lists are created by enclosing a comma-separated sequence of items in square brackets ([]), as shown below:

my_list = [1, 2, 3, 'apple', 'banana', 'cherry']

In this example, the list contains three integers and three strings. The order of the items in the list is preserved.

Lists are very versatile and can hold any type of data, including other lists. They also support various operations, such as indexing, slicing, adding, removing, and sorting elements.

In this section, we will discuss the properties and operations of Python lists in more detail.

Create a Python List

To create a Python list, you can use square brackets [] and separate the values with commas. Here is an example:

my_list = [1, 2, 3, "apple", "banana"]

This creates a list with integers 1, 2, and 3, as well as the strings "apple" and "banana". You can also create an empty list like this:

empty_list = []

Or create a list with a single value:

single_value_list = [42]

Access Python List Elements

To access the elements of a Python list, you can use the indexing operator []. The index of the first element in a list is 0, the second element has an index of 1, and so on. You can also use negative indices to access elements from the end of the list, with -1 being the index of the last element, -2 being the index of the second last element, and so on.

Here's an example:

my_list = ['apple', 'banana', 'cherry']
print(my_list[0])   # Output: 'apple'
print(my_list[2])   # Output: 'cherry'
print(my_list[-1])  # Output: 'cherry'

You can also use slicing to access a range of elements in a list. Slicing is done using the colon : operator. The first number before the colon represents the starting index (inclusive), and the second number after the colon represents the ending index (exclusive).

my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[1:4])  # Output: ['banana', 'cherry', 'orange']

If you omit the first number, Python assumes that you want to start at the beginning of the list. Similarly, if you omit the second number, Python assumes that you want to go until the end of the list.

my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[:3])   # Output: ['apple', 'banana', 'cherry']
print(my_list[2:])   # Output: ['cherry', 'orange', 'kiwi']

You can also use negative indices when slicing. In that case, -1 represents the last element, -2 represents the second last element, and so on.

my_list = ['apple', 'banana', 'cherry', 'orange', 'kiwi']
print(my_list[-3:-1])  # Output: ['cherry', 'orange']

Negative Indexing in Python

Negative indexing in Python allows you to access elements of a list by counting from the end of the list. In other words, the index -1 refers to the last element, -2 refers to the second to last element, and so on.

For example, suppose we have a list my_list = [10, 20, 30, 40, 50]. To access the last element of the list, we can use negative indexing like this:

last_element = my_list[-1]

This would assign the value 50 to the variable last_element. Similarly, we can access the second to last element using -2:

second_to_last = my_list[-2]

This would assign the value 40 to the variable second_to_last.

Slicing of a Python List

Slicing is a technique used in Python to extract a portion of a list by specifying a range of indices. It returns a new list that contains the specified elements.

To slice a Python list, we use the slicing operator :. The syntax for slicing a list is as follows:

list_name[start:end:step]
  • start: The starting index of the slice. If not specified, it defaults to 0.

  • end: The ending index of the slice. If not specified, it defaults to the length of the list.

  • step: The step size of the slice. If not specified, it defaults to 1.

Here are some examples of slicing a Python list:

# Create a list
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

# Slice from index 1 to index 5 (exclusive)
print(my_list[1:5])  # Output: [1, 2, 3, 4]

# Slice from index 2 to the end of the list
print(my_list[2:])  # Output: [2, 3, 4, 5, 6, 7, 8, 9]

# Slice from the beginning of the list to index 4 (exclusive)
print(my_list[:4])  # Output: [0, 1, 2, 3]

# Slice from index 1 to index 7 (exclusive) with a step size of 2
print(my_list[1:7:2])  # Output: [1, 3, 5]

# Reverse the list
print(my_list[::-1])  # Output: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Add Elements to a Python List

Python List provides different methods to add items to a list.

a. Using append()

The append() method is used to add a single element to the end of an existing list.

Here's an example:

my_list = [1, 2, 3, 4]
my_list.append(5)
print(my_list)  # Output: [1, 2, 3, 4, 5]

In this example, we first create a list my_list with elements 1, 2, 3, and 4. We then call the append() method on this list and pass it the argument 5. The append() method adds 5 to the end of the list, and the final output is [1, 2, 3, 4, 5].

b. Using extend()

To add multiple elements to a Python list, you can use the extend() method. This method takes an iterable as an argument and adds each element of the iterable to the end of the list.

Here's an example:

my_list = [1, 2, 3]
my_list.extend([4, 5, 6])
print(my_list)  # Output: [1, 2, 3, 4, 5, 6]

In this example, the extend() method is used to add three elements to the end of the my_list list. The argument passed to extend() is a list [4, 5, 6], which is iterated over and each element is added to the end of the list.

You can also use other iterable objects such as tuples, sets, or even another list with the extend() method.

Change List Items

To change items of a Python list, you can use the indexing and assignment operator = to assign a new value to the desired element of the list.

Here's an example:

# create a list
fruits = ["apple", "banana", "cherry"]

# change the second element (index 1)
fruits[1] = "kiwi"

# print the modified list
print(fruits)

Output:

['apple', 'kiwi', 'cherry']

In the above example, we first created a list of fruits. Then, we used the indexing and assignment operator = to change the second element of the list from banana to kiwi. Finally, we printed the modified list using the print() function.

Remove an Item From a List

1. Using del()

In Python we can use the del statement to remove one or more items from a list. For example,

my_list = ['apple', 'banana', 'cherry', 'orange']

# delete the second element (banana)
del my_list[1]

# print the updated list
print(my_list)

Output:

['apple', 'cherry', 'orange']

In the example above, we first create a list of fruits. Then, using the del keyword, we delete the second element (index 1), which is 'banana'. Finally, we print the updated list to verify that the element has been deleted.

2. Using remove()

The remove() method is used to remove the first occurrence of a specified value from a list.

Syntax: list_name.remove(value)

Example:

fruits = ['apple', 'banana', 'cherry', 'banana']
fruits.remove('banana')
print(fruits)

Output:

['apple', 'cherry', 'banana']

Python List Methods

Python List Methods are built-in functions that allow us to perform operations on Python lists. Some commonly used Python List Methods are:

  1. append(): adds an element to the end of the list.

  2. extend(): adds elements from an iterable to the end of the list.

  3. insert(): adds an element at the specified index.

  4. remove(): removes the first occurrence of the specified element from the list.

  5. pop(): removes the element at the specified index, or the last element if no index is specified, and returns it.

  6. clear(): removes all the elements from the list.

  7. index(): returns the index of the first occurrence of the specified element.

  8. count(): returns the number of times the specified element occurs in the list.

  9. sort(): sorts the list in ascending order.

  10. reverse(): reverses the order of the elements in the list.

These methods help us manipulate the list in various ways and make it more convenient to use.

Operation on List

To perform operations on a Python list, you can use a combination of built-in functions and methods. Some common operations on a Python list include:

  1. Concatenation: You can concatenate two or more lists using the + operator or the extend() method.

  2. Repetition: You can repeat a list a specified number of times using the * operator.

  3. Membership testing: You can test whether an element is present in a list using the in keyword.

  4. Length: You can get the length of a list using the len() function.

  5. Sorting: You can sort a list using the sort() method.

  6. Reversing: You can reverse a list using the reverse() method.

  7. Copying: You can create a copy of a list using the copy() method or the list() constructor.

Here are some examples:

  1. Concatenation:

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
print(list3) # Output: [1, 2, 3, 4, 5, 6]

list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
  1. Repetition:

list1 = [1, 2, 3]
list2 = list1 * 3
print(list2) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
  1. Membership testing:

list1 = [1, 2, 3]
if 2 in list1:
    print("2 is present in the list")
else:
    print("2 is not present in the list")
# Output: 2 is present in the list
  1. Length:

list1 = [1, 2, 3]
length = len(list1)
print(length) # Output: 3
  1. Reversing:

list1 = [1, 2, 3]
list1.reverse()
print(list1) # Output: [3, 2, 1]
  1. Sorting:

list1 = [3, 1, 2]
list1.sort()
print(list1) # Output: [1, 2, 3]
  1. Copying:

list1 = [1, 2, 3]
list2 = list1.copy()
list3 = list(list1)
print(list2) # Output: [1, 2, 3]
print(list3) # Output: [1, 2, 3]

Function on List

To perform a function on a Python list, you can use various built-in functions provided by Python.

Here are some commonly used functions on a Python list:

  1. len(): This function returns the number of elements in the list.

  2. max(): This function returns the largest element in the list.

  3. min(): This function returns the smallest element in the list.

  4. sum(): This function returns the sum of all elements in the list.

  5. sorted(): This function returns a sorted list.

  6. reversed(): This function returns a reversed list.

  7. any(): This function returns True if at least one element in the list is True, otherwise it returns False.

  8. all(): This function returns True if all elements in the list are True, otherwise it returns False.

  9. enumerate(): This function returns an iterator of tuples containing the index and the value of each element in the list.

  10. zip(): This function returns an iterator of tuples where each tuple contains the elements from the input lists at that index.

  11. filter(): This function returns a new list containing only the elements for which the given function returns True.

  12. map(): This function applies the given function to each element in the list and returns a new list containing the results.

  13. reduce(): This function applies the given function to the first two elements in the list, then applies the function to the result and the next element in the list, and so on, until all elements have been processed. The final result is returned. Note that reduce() is not a built-in function in Python 3, but is available in the functools module.

To perform a function on a Python list, you can use various built-in functions provided by Python. Here are some examples:

  1. len(): This function returns the length of the list, i.e., the number of elements in the list.

Example:

my_list = [1, 2, 3, 4, 5]
print(len(my_list))

Output:

5
  1. sum(): This function returns the sum of all elements in the list.

Example:

my_list = [1, 2, 3, 4, 5]
print(sum(my_list))

Output:

15
  1. max(): This function returns the maximum value from the list.

Example:

my_list = [1, 2, 3, 4, 5]
print(max(my_list))

Output:

5
  1. min(): This function returns the minimum value from the list.

Example:

my_list = [1, 2, 3, 4, 5]
print(min(my_list))

Output:

1
  1. sorted(): This function returns a new sorted list.

Example:

my_list = [5, 3, 1, 4, 2]
sorted_list = sorted(my_list)
print(sorted_list)

Output:

[1, 2, 3, 4, 5]
  1. reversed(): This function returns a new reversed list.

Example:

my_list = [1, 2, 3, 4, 5]
reversed_list = list(reversed(my_list))
print(reversed_list)

Output:

[5, 4, 3, 2, 1]

Last updated