Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Built-In Data Types
  5. List in Python

List in Python

A list in Python is an ordered, mutable (changeable) collection of items, enclosed in square brackets [ ].

  • Lists can hold elements of different data types including numbers, strings, or even other lists.
  • Indexing is used to access individual elements using their position (starting at index 0).
  • Slicing extracts a range of elements using start:stop syntax.

Example:

lst = [10, 20, 30, 40, 50]
print(lst[0])      # Output: 10
print(lst[1:3])    # Output: [20, 30]

Lists are mutable, so you can change their elements after creation.

Example:

lst[0] = 100
print(lst)         # Output: [100, 20, 30, 40, 50]
  • Use append() to add to the end.
  • Use insert() to add at a specific position.
  • Use remove() to delete a specific value.
  • Use pop() to remove by index (or last item if no index is given).

Example:

lst.append(60)
lst.insert(1, 15)
lst.remove(30)
lst.pop(2)
print(lst)  # Output might vary depending on operations

Example:

for item in lst:
    print(item)

To avoid modifying the original list, use copy() or slicing.

Example:

new_lst = lst.copy()
# OR
new_lst = lst[:]

A compact way to create lists from an iterable.

Example:

squares = [x*x for x in range(5)]
print(squares)     # Output: [0, 1, 4, 9, 16]
  • Use sort() to sort the list in-place.
  • Use sorted() to get a new sorted list.

Example:

numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers)     # Output: [1, 2, 3, 4]

To join list elements into a string, use join() (only works with strings).

Example:

letters = ["a", "b", "c"]
result = ", ".join(letters)
print(result)      # Output: a, b, c

How can we help?

Leave a Reply

Your email address will not be published. Required fields are marked *