Container Data Structures

Lists in Detail

Lists and tuples can contain items of mixed types and the type of any item can be retrieved by using the type()function:

list_of_mixed_items = ['red', 2.3, 4, True,
                       ["another", "list"],
                       ("a" , "tuple"),
                       {"a" , "set"},
                       {"and": 1, "a": 2, "dictionary": 3}]

for item in list_of_mixed_items:
    print(type(item))

Output:

<class 'str'>
<class 'float'>
<class 'int'>
<class 'bool'>
<class 'list'>
<class 'tuple'>
<class 'set'>
<class 'dict'>
color = "yellow"
number = 10
boolean = True

sublist = [123, 213]

tuple_of_mixed_items = (color, number, boolean, sublist)

color = "red"
number = 11
boolean = False

sublist[0] = 34
sublist.append(54)

for item in tuple_of_mixed_items:
    print(item)

sublist = [36, 67]
print(tuple_of_mixed_items)

mylist=[color,number]
print(mylist)
color = "blue"
print(mylist)

Output:

yellow
10
True
[34, 213, 54]
('yellow', 10, True, [34, 213, 54])

Elements in a tuple can be assigned (unpacked) to multiple variables at once, possibly as a list when using an asterisk (*) to contain all items left without a variable:

person = (23, "Ghida", "Student", 20009001, "Reading", "Maths", "Address", "ghida@some.mail")
age, name, occupation, id, *other_info, email = person

print(age)
print(name)
print(occupation)
print(id)
print(other_info)
print(email)

Output:

23
Ghida
Student
20009001
['Reading', 'Maths', 'Adress']
ghida@some.mail

The star * notation can be used to unpack list items. Execute the following code and compare the outputs:

my_list = ["purple", "red"]

print(my_list)

print(*my_list)

Displaying a chess board with * operator:


chess_board =[['r','n','b','q','k','b','n','r'],\
              ['p','p','p','p','p','p','p','p'],\
              ['.','.','.','.','.','.','.','.'],\
              ['.','.','.','.','.','.','.','.'],\
              ['.','.','.','.','.','.','.','.'],\
              ['.','.','.','.','.','.','.','.'],\
              ['P','P','P','P','P','P','P','P'],\
              ['R','N','B','Q','K','B','N','R']]

for i in range (8):
    print((" " if i > 7 else (8-i)), *chess_board[i])

print(" ", *['a','b','c','d','e','f','g','h'])

""" The output is as follows:

8 r n b q k b n r
7 p p p p p p p p
6 . . . . . . . .
5 . . . . . . . .
4 . . . . . . . .
3 . . . . . . . .
2 P P P P P P P P
1 R N B Q K B N R
  a b c d e f g h

"""

When used in a function definition, the star * notation stands for 'arbitrary number of parameters':

def add_numbers(*numbers):
   return sum(numbers)

print(add_numbers(5, 10, 20, 6))

print(add_numbers(50, 21))