Learning Python: Handling Lists, List Functions, Dictionaries, Tuples

Learning Python: Handling Lists, List Functions, Dictionaries, Tuples

In Python, a list is a dynamic data structure. This means that the size of a list can change after it is initialized: new elements can be added to the list and old elements can be deleted. In addition, the elements of a list can be replaced by other elements.

numbers = [4, 8, 15, 16, 23, 42]        

A list can contain different types of elements, data structures or variables.

>>> universe = 42

>>> colors = ["red", "green", "blue"]

>>> mixed_list = [99, "neon", colors, universe]

>>> mixed_list
[99, 'neon', ['red', 'green', 'blue'], 42]        

The elements of the list are referenced in the same way as the characters in the string: by hook notation and indexes (starting from 0).

>>> mixed_list[2]
['red', 'green', 'blue']        

The length of the list is returned by the len() function.

>>> len(mixed_list)
4        

A new element can be added to the list with the append() method. The new element is added at the end of the list.

The method can also accept variable references and operations.

>>> mixed_list.append(mixed_list[0] + universe)

>>> mixed_list
[99, 'neon', ['red', 'green', 'blue'], 42, 141]        

Example: Swap the first and last elements of the list.

>>> mixed_list[0], mixed_list[-1] = mixed_list[-1], mixed_list[0]

>>> mixed_list
[141, 'neon', ['red', 'green', 'blue'], 42, 99]        

The range() function can be used to create a series of values that can be iterated through using the for statement. The final step is not included in the generated series. For example, a call to range(1, 10) returns a series of numbers from 1 to 9.

Example: Sum the integers from 1 to 10,000.

>>> sum = 0

>>> for i in range(1, 10001):
...     sum += i
... 

>>> print(sum)
50005000        

A third parameter, the step, can also be given to the series.

Example: Print every 5th element in a list. Use a list of the first 30 numbers in the Fibonacci sequence.

def fibonacci(n):
    # The first two numbers in the Fibonacci series
    n1 = 1
    n2 = 1
    # Fibonacci sequence list
    fibonacci_list = [n1, n2]
    counter = 0
    while len(fibonacci_list) < n:
        sum = n1 + n2
        fibonacci_list.append(sum)
        # Update the values
        n1 = n2
        n2 = sum
        counter += 1
    return fibonacci_list

fibo_numbers = fibonacci(30)

print(fibo_numbers)

for i in range(0, len(fibo_numbers), 5):
    print(fibo_numbers[i])        

Output:

# Full list
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040]

# Every 5th element
1
8
89
987
10946
121393        

Example: From a list of 50 randomly generated numbers (between 1 and 100), sort odd and even numbers to separate lists.

import random

random_numbers = [random.randint(1, 100) for _ in range(50)]

odd_numbers = []

even_numbers = []

for n in random_numbers:
    if n % 2 == 0:
        even_numbers.append(n)
    else:
        odd_numbers.append(n)

>>> random_numbers
[91, 78, 81, 63, 77, 52, 40, 38, 93, 20, 20, 76, 70, 58, 48, 77, 9, 70, 27, 80, 90, 77, 49, 12, 31, 8, 79, 62, 41, 77, 62, 6, 92, 51, 95, 49, 72, 95, 69, 56, 13, 24, 71, 36, 75, 74, 10, 34, 45, 94]

>>> odd_numbers
[91, 81, 63, 77, 93, 77, 9, 27, 77, 49, 31, 79, 41, 77, 51, 95, 49, 95, 69, 13, 71, 75, 45]

>>> even_numbers
[78, 52, 40, 38, 20, 20, 76, 70, 58, 48, 70, 80, 90, 12, 8, 62, 62, 6, 92, 72, 56, 24, 36, 74, 10, 34, 94]        

Since a list is mutable data structure, the order of its elements can be changed. The elements of a list can be arranged in a natural order from the lowest to the highest using the sort() method.

The sorted() function will preserve the order of the elements in the original list and create an ordered copy of the original list.

NOTE: sort() is a method and sorted() is a function, so they are called differently.

Example:

import random

bingo_numbers = [random.randint(1, 75) for _ in range(25)]

sorted_bingo = sorted(bingo_numbers)

print(f"Original: {bingo_numbers}")

print(f"sorted(): {sorted_bingo}")

bingo_numbers.sort()

print(f"Original - after sort(): {bingo_numbers}")        

Output:

Original: [64, 18, 75, 37, 4, 6, 22, 69, 35, 71, 21, 41, 49, 42, 40, 49, 23, 56, 47, 22, 33, 34, 65, 74, 5]

sorted(): [4, 5, 6, 18, 21, 22, 22, 23, 33, 34, 35, 37, 40, 41, 42, 47, 49, 49, 56, 64, 65, 69, 71, 74, 75]

Original - after sort(): [4, 5, 6, 18, 21, 22, 22, 23, 33, 34, 35, 37, 40, 41, 42, 47, 49, 49, 56, 64, 65, 69, 71, 74, 75]        

The order of the elements in the list can be reversed with the reverse() method.

# Code
bingo_numbers.reverse()
print(f"Original - after reverse(): {bingo_numbers}")

# Output
Original - after reverse(): [75, 74, 71, 69, 65, 64, 56, 49, 49, 47, 42, 41, 40, 37, 35, 34, 33, 23, 22, 22, 21, 18, 6, 5, 4]        

The occurrence of a list element can be viewed using the in operator. The index of the element can be found by using the index() method.

NOTE: The index() method will return an error if trying to retrieve an instance of an element that is not in a list. So before using the index() method, it is a good idea to check the occurrence of the element with the in operator.

# Code
for num in range(10):
    if num in bingo_numbers:
        print(f"{num} is found at index", bingo_numbers.index(num))

# Output
4 is found at index 24
5 is found at index 23
6 is found at index 22        

Other handy list functions are at least min(), max() and sum().

# Code
print("Largest value:", max(bingo_numbers))
print("Smallest value:", min(bingo_numbers))
print("Sum:", sum(bingo_numbers))

# Output
Largest value: 75
Smallest value: 4
Sum: 1002        

Any type of data can be stored in lists and different types of values can be stored in the same list. However, this is usually a bad idea, as it can lead to various error situations. In general, the elements of a list should all be of the same type.

>>> mixed_list = [11, 42, "Alice", 7.55, True, "Bob", False]

>>> for element in mixed_list:
...     print(element + 10)
... 

>>> 
21
52
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: can only concatenate str (not "int") to str        

A dictionary is a data structure where keys point to elements. The elements are in no particular order. However, a value can be extracted from the dictionary very quickly if the key is known.

>>> students = {
    "S1234": "Eldarion Shadowblade",
    "S2345": "Luna Evergreen",
    "S3456": "Ariadne Stormwind",
    "S4567": "Draven Nightmare",
    "S5678": "Thalia Silverleaf"
}

>>> print(students["S4567"])
Draven Nightmare        

NOTE: If the key already exists in the dictionary, the old value will be replaced by the new one.

>>> students["S5678"] = "Lilith Darkbane"

>>> students
{'S1234': 'Eldarion Shadowblade', 'S2345': 'Luna Evergreen', 'S3456': 'Ariadne Stormwind', 'S4567': 'Draven Nightmare', 'S5678': 'Lilith Darkbane'}        

If the key does not exist, an error occurs. This is similar to trying to retrieve an element from a list using an index that does not exist in the list.

>>> print(students["S01234"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'S01234'        

A tuple is a data structure that resembles a list. However, unlike a list, a tuple is immutable. This means that the elements of a tuple cannot be changed once it has been created, nor can you add or remove elements from a tuple.

Tuples are intended to form value groups. They can therefore be used to easily combine related values into a single structure.

>>> flag = ("blue", "yellow")

>>> flag
('blue', 'yellow')

>>> flag[1] = "white"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment        

Although a tuple cannot be changed, it can be replaced with a new tuple.

>>> flag = ("blue", "white")

>>> flag
('blue', 'white')        

Example: Create a deck of cards.

deck = []

suits = ["hearts", "diamonds”, “clubs", "spades"]

for value in range(1, 14):
    for suit in suits:
        card = (suit, value)
        deck.append(card)        

Entries can be removed from a dictionary and a list using the del keyword. A tuple is immutable and the elements cannot be removed.

>>> coordinates = [(4, 6), (3, 4), (2, 5), (10, 9)

>>> coordinates
[(4, 6), (3, 4), (2, 5), (10, 9)]

>>> del coordinates[2]

>>> coordinates
[(4, 6), (3, 4), (10, 9)]        

NOTE: In the example, the tuples can be removed because they are elements in a list.

Removing elements inside the loop can mess up the iteration. Deleting an element can cause the loop to skip over the next element and eventually the loop execution will end in an error because the list is shorter than expected.

Example: Create a list of 20 numbers (from 1 to 100) and remove all even numbers.

import random

numbers = [random.randint(1, 100) for _ in range(20)]
print(numbers)

for n in numbers:
    if n % 2 == 0:
        del numbers[n]

print(numbers)        

Output:

[10, 28, 28, 20, 56, 69, 7, 55, 26, 22, 45, 85, 10, 33, 85, 44, 59, 33, 90, 69]

Traceback (most recent call last):
  File "test.py", line 8, in <module>
    del numbers[n]
IndexError: list assignment index out of range        

Deleting elements in a loop must done in some other way, for example, with a while statement or by copying the stored elements to another data structure instead of deleting them.

Example: Using a while loop to fix the out of range error.

import random

numbers = [random.randint(1, 100) for _ in range(20)]
print(numbers)

index = 0 

while index < len(numbers):
    if numbers[index] % 2 == 0:
        del numbers[index]
    else:
        index += 1

print(numbers)        

Output:

[95, 80, 33, 98, 46, 98, 84, 56, 50, 57, 89, 3, 37, 63, 15, 12, 52, 19, 71, 83]

[95, 33, 57, 89, 3, 37, 63, 15, 19, 71, 83]        



Vincent Hoang

CCNA | VCP-DCV6 | VCP-DCV7 | JNCIA | OCI | RCNA | NSE1-3| FCA

11 个月

Thank you for sharing your knowledge to community, i learned a lot from your post. ??

要查看或添加评论,请登录

Riikka Sihvonen的更多文章

社区洞察

其他会员也浏览了