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