Day 44: Lists, Sets and Tuples

# list - holds a list of objects
# can be of any type and mix them
# lists are mutable

names = []                      # create an empty list
names_1 = ["Harvey", "Charles"] # create a populated list

# with list a string will return as individual chars
custom_list = list("Robert")

print(custom_list)              # ['R', 'o', 'b', 'e', 'r', 't']

# get specific items with index (index starts at 0)
print(names_1[0])               # Harvey
print(names_1[1])               # Charles

#list insertion

#insert an item with index
names_1.insert(1, "Dave")
print(names_1)                  # ['Harvey', 'Dave', 'Charles']

#append an item at the end of the list
names_1.append("Clara")
print(names_1)                  # ['Harvey', 'Dave', 'Charles', 'Clara']

#replace an item with index
names_1[1] = "Sophie"
print(names_1)                  # ['Harvey', 'Sophie', 'Charles', 'Clara']

# delete an list item
#1
names_1.remove("Harvey")
print(names_1)                  # ['Sophie', 'Charles', 'Clara']

#2
del names_1[2]
print(names_1)                  # ['Sophie', 'Charles']

# sorting a list

# sort strings alphabetically
names_1.sort()
print(names_1)                  # ['Charles', 'Sophie']

# sort numbers
numbers = [3,2,7,-3,99]
print(numbers)                  # [3, 2, 7, -3, 99]

numbers.sort()
print(numbers)                  # [-3, 2, 3, 7, 99]

# ATTENTION: You can't sort numbers and strings in one list -> error

#example

# tuples - holds unmutable items
# tuples can't be changed
# tuples can serve as keys in dictionaries
# ideal for unchanging values like pi or 24 hours

# crate a tuple
tuple_name = ("Steven", "Alice", "Vincent")

print (tuple_name)

print(tuple_name[1])                # Alice

# cannot append to tuples

# Sets
# sets are mutable and don't care about order
# they are great to check membership, remove duplicates and are hashable

digits = [0,1,1,2,3,4,4,5,6,7,8.5,9]

digit_set =  set(digits)        # removes duplicates

print(digit_set)                # Output: {0, 1, 2, 3, 4, 5, 6, 7, 8.5, 9}

print(9 in digit_set)           # True - checks if 9 is a member of the sets

# you can add or remove other Sets
even = {2,4,6,8,10}                # note we are using {} here instead of []

odd = digit_set - even              # remove even from digit_set

print(odd)                          # Output {0, 1, 3, 5, 7, 8.5, 9}

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.