Basics of lists in Python: creation, methods and use for storage and processing of data collections

Treinador Online de Python para Iniciantes

Aprenda Python facilmente sem sobrecarga teórica. Resolva tarefas práticas com verificação automática e escreva código diretamente no navegador.

Start Course

Tutorial de Python 3 para iniciantes.

Python lists are ordered mutable collections of objects of arbitrary types. They are one of the most flexible and frequently used data types in Python programming. Let's take a closer look at the creation, use, and interaction of lists with various types of data.

Creating lists in Python

Empty list

empty_list = []

A list with

elements
numbers = [1, 2, 3, 4, 5]
strings = ["apple", "banana", "cherry"]
mixed = [1, "apple", 3.14, True]

Creating lists using the list() constructor

# Creating a list from a string
letters = list("hello")
print(letters) # ['h', 'e', 'l', 'l', 'o']

# Creating a list from a range
of numbers = list(range(5))
print(numbers) # [0, 1, 2, 3, 4]

Accessing list items

Indexing of elements

fruits = ["apple", "banana", "cherry"]
# Accessing elements from the beginning
print(fruits[0])  # apple
print(fruits[1])  # banana
print(fruits[2])  # cherry

# Accessing elements from the end
print(fruits[-1]) # cherry
print(fruits[-2]) # banana
print(fruits[-3]) # apple

Slicing

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4]
print(numbers[:3])     # [0, 1, 2]
print(numbers[7:])     # [7, 8, 9]
print(numbers[::2])    # [0, 2, 4, 6, 8]
print(numbers[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Changing list items

fruits = ["apple", "banana", "cherry"]
fruits[1] = "blueberry"
print(fruits)  # ['apple', 'blueberry', 'cherry']

# Changing multiple elements through a slice
fruits[1:3] = ["orange", "grape"]
print(fruits)  # ['apple', 'orange', 'grape']

Adding items to the list

The append() method

Adds an item to the end of the list.

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)  # ['apple', 'banana', 'cherry']

Insert() method

Inserts the element at the specified position.

fruits = ["apple", "banana"]
fruits.insert(1, "blueberry")
print(fruits)  # ['apple', 'blueberry', 'banana']

Extend() method

Expands the list by adding all the elements from the passed iterable object to the end.

fruits = ["apple", "banana"]
more_fruits = ["cherry", "date"]
fruits.extend(more_fruits)
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

The += operator for adding elements

fruits = ["apple", "banana"]
fruits += ["cherry", "date"]
print(fruits)  # ['apple', 'banana', 'cherry', 'date']

Removing items from the list

The remove() method

Deletes the first occurrence of the specified value.

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

The pop() method

Deletes and returns the element at the specified index.

fruits = ["apple", "banana", "cherry"]
popped_fruit = fruits.pop(1)
print(popped_fruit)  # banana
print(fruits)  # ['apple', 'cherry']

# Deleting the last element
last_fruit = fruits.pop()
print(last_fruit) # cherry

The del operator

fruits = ["apple", "banana", "cherry", "date"]
del fruits[1] # Deletes element by index
del fruits[1:3] # Deletes slice
print(fruits)

Clear() method

Deletes all items from the list.

fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)  # []

Searching for items in the list

The index() method

Returns the index of the first occurrence of the specified value.

fruits = ["apple", "banana", "cherry"]
index = fruits.index("banana")
print(index)  # 1

# Search with a range
of numbers = [1, 2, 3, 2, 4, 2, 5]
index = numbers.index(2, 2, 6) # Searches for 2 in the range [2:6]
print(index)  # 3

Count() method

Returns the number of occurrences of the specified value.

numbers = [1, 2, 2, 3, 2]
count = numbers.count(2)
print(count)  # 3

The in operator for checking the presence of an element

fruits = ["apple", "banana", "cherry"]
print("banana" in fruits)     # True
print("orange" not in fruits) # True

Sorting the list

Sort() method

Sorts the list in place.

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.sort()
print(numbers)  # [1, 1, 2, 3, 4, 5, 9]

# Sort in reverse order
numbers.sort(reverse=True)
print(numbers) # [9, 5, 4, 3, 2, 1, 1]

# Sorting strings by length
words = ["python", "java", "c", "javascript"]
words.sort(key=len)
print(words)  # ['c', 'java', 'python', 'javascript']

sorted() function

Returns a new sorted list.

numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers)  # [1, 1, 2, 3, 4, 5, 9]
print(numbers)         # [3, 1, 4, 1, 5, 9, 2] ( the original one has not changed)

List Conversion

The reverse() method

Reverses the order of the items in the list.

numbers = [3, 1, 4, 1, 5, 9, 2]
numbers.reverse()
print(numbers)  # [2, 9, 5, 1, 4, 1, 3]

Function reversed()

Returns an iterator with the elements in reverse order.

numbers = [3, 1, 4, 1, 5, 9, 2]
reversed_numbers = list(reversed(numbers))
print(reversed_numbers)  # [2, 9, 5, 1, 4, 1, 3]

Copying lists

Surface copying

# Method copy()
original = [1, 2, 3]
copy = original.copy()
print(copy) # [1, 2, 3]

# Slice
copy = original[:]
print(copy) # [1, 2, 3]

# List() constructor
copy = list(original)
print(copy)  # [1, 2, 3]

Deep copy

To deeply copy nested lists, use the copy module.

import copy

original = [[1, 2, 3], [4, 5, 6]]
deep_copy = copy.deepcopy(original)
shallow_copy = copy.copy(original)

original[0][0] = 999
print(original)      # [[999, 2, 3], [4, 5, 6]]
print(shallow_copy)  # [[999, 2, 3], [4, 5, 6]]
print(deep_copy)     # [[1, 2, 3], [4, 5, 6]]

Table of basic list methods

method
TheDescription Usage example
append(x) Adds the x element to the end of the list lst.append(3)
extend(iterable) Expands the list by adding all the elements from the iterated object lst.extend([4, 5])
insert(i, x) Inserts element x at position i lst.insert(1, 2)
remove(x) Deletes the first element with the value x lst.remove(3)
pop([i]) Deletes and returns an element at position i lst.pop(), lst.pop(1)
clear() Deletes all items from the list lst.clear()
index(x) Returns the index of the first element with the value x lst.index(3)
count(x) Returns the number of elements with the value x lst.count(3)
sort() Sorts the list in place lst.sort()
reverse() Expands the list in place lst.reverse()
copy() Returns a shallow copy of the list lst.copy()

Lists and various data types

Lists with strings

words = ["hello", "world", "python"]
joined = " ".join(words)
print(joined)  # "hello world python"

split_words = joined.split()
print(split_words)  # ['hello', 'world', 'python']

# Sorting rows
words.sort()
print(words)  # ['hello', 'python', 'world']

Lists with numbers

numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares)  # [1, 4, 9, 16, 25]

# Mathematical operations
print(sum(numbers))    # 15
print(max(numbers))    # 5
print(min(numbers))    # 1

Lists with boolean values

booleans = [True, False, True]
all_true = all(booleans)
any_true = any(booleans)
print(all_true)  # False
print(any_true)  # True

Multidimensional lists

# Two-dimensional list (matrix)
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Access to the elements
print(matrix[0][1])  # 2
print(matrix[2][0])  # 7

# Iterating over the matrix
for row in matrix:
    for elem in row:
        print(elem, end=' ')
    print()

Iterating through lists

Simple iteration

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Iteration with indexes

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"Index {index}: {fruit}")

# Iterating with range()
for i in range(len(fruits)):
    print(f"Index {i}: {fruits[i]}")

Iterating over multiple lists

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

List Comprehensions

Basic list generators

# Simple
squares generator = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Generator with the condition
even_squares = [x ** 2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]

# Complex generator
words = ["hello", "world", "python"]
uppercase_words = [word.upper() for word in words if len(word) > 4]
print(uppercase_words)  # ['HELLO', 'WORLD', 'PYTHON']

Nested list generators

#
Matrix creation matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# Converting a matrix to a flat list
flat_list = [item for row in matrix for item in row]
print(flat_list)  # [1, 2, 3, 2, 4, 6, 3, 6, 9]

Built-in functions for working with lists

The len() function

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

Functions sum(), max(), min()

numbers = [1, 2, 3, 4, 5]
print(sum(numbers))  # 15
print(max(numbers))  # 5
print(min(numbers))  # 1

zip() function

names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["New York", "Los Angeles", "Chicago"]

for name, age, city in zip(names, ages, cities):
    print(f"{name} is {age} years old and lives in {city}")

map() function

numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# Applying a function to strings
words = ["hello", "world"]
upper_words = list(map(str.upper, words))
print(upper_words)  # ['HELLO', 'WORLD']

filter() function

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6, 8, 10]

# String filtering
words = ["python", "java", "c", "javascript", "go"]
long_words = list(filter(lambda word: len(word) > 3, words))
print(long_words)  # ['python', 'java', 'javascript']

Reduce() function

from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 120

# Finding the maximum
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum)  # 5

Useful list operations

Rotating the list

def rotate_list(lst, k):
"""Rotates the list k positions to the right"""
n = len(lst)
k = k % n # Handling cases when k is longer than the list length
    return lst[-k:] + lst[:-k]

numbers = [1, 2, 3, 4, 5]
rotated = rotate_list(numbers, 2)
print(rotated)  # [4, 5, 1, 2, 3]

Removing duplicates

# An easy way (does not preserve the order)
of numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)  # [1, 2, 3, 4, 5]

# Preserving the order
of def remove_duplicates(lst):
    seen = set()
    result = []
    for item in lst:
        if item not in seen:
            seen.add(item)
            result.append(item)
    return result

numbers = [1, 2, 2, 3, 4, 4, 5]
unique_ordered = remove_duplicates(numbers)
print(unique_ordered)  # [1, 2, 3, 4, 5]

Splitting the list into parts

def chunk_list(lst, n):
"""Divides the list into parts of size n"""
    return [lst[i:i + n] for i in range(0, len(lst), n)]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
chunks = chunk_list(numbers, 3)
print(chunks)  # [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

List comparison

list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = [3, 2, 1]

print(list1 == list2)  # True
print(list1 == list3)  # False
print(list1 is list2)  # False

# Comparing the content without taking into account the order
print(set(list1) == set(list3))  # True

Combining lists

list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = [7, 8, 9]

# Different ways to combine
combined1 = list1 + list2 + list3
combined2 = [*list1, *list2, *list3]
combined3 = []
combined3.extend(list1)
combined3.extend(list2)
combined3.extend(list3)

print(combined1)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

Performance and optimization

Choosing between append() and extend()

# Slower for adding multiple
lst elements = []
for item in [1, 2, 3, 4, 5]:
    lst.append(item)

# Faster for adding multiple elements
lst = []
lst.extend([1, 2, 3, 4, 5])

Using list generators instead of loops

# Slower
squares = []
for x in range(1000):
    squares.append(x ** 2)

# Faster
squares = [x ** 2 for x in range(1000)]