Learn Python Programming  /  Data Structures  /  List

List

A list is Python's most commonly used data structure โ€” an ordered, changeable collection that can hold items of any type, including a mix of types.

Creating a List

R Code
ages = [20, 22, 19, 25]
mixed = ["Rafi", 23, True]   # lists can mix types

print(ages)
print(mixed)
Output
[20, 22, 19, 25]
['Rafi', 23, True]

Indexing โ€” Python Starts at 0

R Code
fruits = ["apple", "banana", "mango", "grape", "kiwi"]

print(fruits[0])    # first element
print(fruits[-1])   # last element
print(fruits[1:4])  # slice: index 1 up to (not including) 4
Output
apple
kiwi
['banana', 'mango', 'grape']
⚠ Common Mistake
Python indexing starts at 0, not 1 (unlike R). fruits[1] is the SECOND item, not the first. This is one of the most common early bugs when switching between R and Python.

Modifying a List

R Code
fruits = ["apple", "banana", "mango"]

fruits.append("kiwi")      # add to the end
fruits.insert(1, "grape") # insert at a specific position
fruits.remove("banana")   # remove by value
fruits[0] = "apricot"       # update by index

print(fruits)
Output
['apricot', 'grape', 'mango', 'kiwi']

Useful List Methods

R Code
nums = [23, 9, 45, 12, 9, 30]

print(len(nums))          # number of elements
print(sum(nums))          # total
print(max(nums), min(nums))
print(sorted(nums))       # new sorted list, original unchanged
nums.sort(reverse=True) # sorts the list itself, descending
print(nums)
print(nums.count(9))    # how many times 9 appears
Output
6
128
45 9
[9, 9, 12, 23, 30, 45]
[45, 30, 23, 12, 9, 9]
2

Copying a List Safely

R Code
original = [1, 2, 3]
shallow = original          # NOT a copy - same list, two names
real_copy = original.copy()  # an actual independent copy

shallow.append(4)
print(original)      # changed too! shallow was never a separate list
print(real_copy)
Output
[1, 2, 3, 4]
[1, 2, 3]
⚠ Common Mistake
new_list = old_list does NOT create a copy - it creates a second name pointing at the exact same list in memory. Modifying one modifies the other. Always use .copy() (or list(old_list)) when you need an independent list.

Advanced: List Comprehension

🚀 Advanced Example
A list comprehension builds a new list in a single, readable line - the most 'Pythonic' way to transform or filter a list, and usually faster than an equivalent for loop.
R Code
nums = [1, 2, 3, 4, 5, 6]

squares = [x**2 for x in nums]
evens_only = [x for x in nums if x % 2 == 0]

print(squares)
print(evens_only)
Output
[1, 4, 9, 16, 25, 36]
[2, 4, 6]

Key Points

  • Lists are ordered, changeable, and can hold mixed types.
  • Indexing starts at 0; negative indices count from the end; slicing uses start:stop (stop is excluded).
  • Use .copy() to get an independent copy - plain assignment just creates a second name for the same list.
  • A list comprehension [expr for item in list if condition] is the idiomatic way to transform or filter a list.