Skip to main content

Command Palette

Search for a command to run...

Python Lists

Updated
4 min readView as Markdown
Python Lists

Let's delve into the various aspects of Python lists, exploring how to access, change, add, remove, loop through, use list comprehensions, sort, copy, join, and utilize list methods.

1. Accessing Elements:

  • Use square brackets [] to access elements.

  • Python lists are zero-indexed.

#!/usr/bin/python3
pythonCopy codenumbers = [1, 2, 3, 4, 5]
first_element = numbers[0]  # Output: 1
third_element = numbers[2]  # Output: 3

2. Changing Elements:

  • Lists are mutable; you can change individual elements.
#!/usr/bin/python3
pythonCopy codenumbers[1] = 10
print(numbers)  # Output: [1, 10, 3, 4, 5]

3. Adding Elements:

  • Use append() to add an element at the end.

  • Use insert() to add at a specific index.

#!/usr/bin/python3
pythonCopy codenumbers.append(6)
numbers.insert(2, 7)
print(numbers)  # Output: [1, 10, 7, 3, 4, 5, 6]

4. Removing Elements:

  • Use remove() to remove a specific value.

  • Use pop() to remove by index.

#!/usr/bin/python3
pythonCopy codenumbers.remove(7)
popped_value = numbers.pop(2)
print(numbers)      # Output: [1, 10, 3, 4, 5, 6]
print(popped_value)  # Output: 7

5. Looping Through a List:

  • Use for loop to iterate through elements.
#!/usr/bin/python3
pythonCopy codefor number in numbers:
    print(number)

6. List Comprehensions:

  • Concise way to create lists.
#!/usr/bin/python3
pythonCopy codesquared_numbers = [x**2 for x in numbers]

7. Sorting a List:

  • Use sort() for in-place sorting.

  • Use sorted() for creating a new sorted list.

#!/usr/bin/python3
pythonCopy codenumbers.sort()
sorted_numbers = sorted(numbers, reverse=True)

8. Copying a List:

  • Create a shallow copy using copy().

  • Create a deep copy using copy.deepcopy().

#!/usr/bin/python3
pythonCopy codeshallow_copy = numbers.copy()

9. Joining Lists:

  • Use + or extend() to concatenate lists.
#!/usr/bin/python3
pythonCopy codemore_numbers = [7, 8, 9]
combined_list = numbers + more_numbers
numbers.extend(more_numbers)

10. List Methods:

  • Methods like count(), index(), and clear().
#!/usr/bin/python3
pythonCopy codecount_of_4 = numbers.count(4)
index_of_5 = numbers.index(5)
numbers.clear()

Example:

#!/usr/bin/python3
pythonCopy code# Example List
numbers = [1, 2, 3, 4, 5]

# Accessing Elements
first_element = numbers[0]

# Changing Elements
numbers[1] = 10

# Adding Elements
numbers.append(6)
numbers.insert(2, 7)

# Removing Elements
numbers.remove(7)
popped_value = numbers.pop(2)

# Looping Through a List
for number in numbers:
    print(number)

# List Comprehension
squared_numbers = [x**2 for x in numbers]

# Sorting a List
numbers.sort()
sorted_numbers = sorted(numbers, reverse=True)

# Copying a List
shallow_copy = numbers.copy()

# Joining Lists
more_numbers = [7, 8, 9]
combined_list = numbers + more_numbers
numbers.extend(more_numbers)

# List Methods
count_of_4 = numbers.count(4)
index_of_5 = numbers.index(5)
numbers.clear()

Understanding these operations equips you with powerful tools for manipulating lists in Python.

Introduction of additional methods for the list data type in Python. Here is a summary of these methods:

  1. list.append(x):

    • Adds an item to the end of the list.

    • Equivalent to a[len(a):] = [x].

  2. list.extend(iterable):

    • Extends the list by appending all items from the iterable.

    • Equivalent to a[len(a):] = iterable.

  3. list.insert(i, x):

    • Inserts an item at a given position.

    • The first argument is the index of the element before which to insert.

    • a.insert(0, x) inserts at the front, and a.insert(len(a), x) is equivalent to a.append(x).

  4. list.remove(x):

    • Removes the first item from the list whose value is equal to x.

    • Raises a ValueError if there is no such item.

  5. list.pop([i]):

    • Removes the item at the given position in the list and returns it.

    • If no index is specified, a.pop() removes and returns the last item in the list.

    • Square brackets denote optional parameters.

  6. list.clear():

    • Removes all items from the list.

    • Equivalent to del a[:].

  7. list.index(x[, start[, end]]):

    • Returns the zero-based index in the list of the first item whose value is equal to x.

    • Raises a ValueError if there is no such item.

    • Optional arguments start and end limit the search to a particular subsequence.

  8. list.count(x):

    • Returns the number of times x appears in the list.
  9. list.sort(*, key=None, reverse=False):

    • Sorts the items of the list in place.

    • Arguments can be used for sort customization.

  10. list.reverse():

    • Reverses the elements of the list in place.
  11. list.copy():

    • Returns a shallow copy of the list.

    • Equivalent to a[:].