home

Built-In Collections

List

x = [1, 'a', 2, 'b']
print(type(x))
# <class 'list'>

Creating a List of Sequential Numbers using range

start = 5
stop = 10

my_nums = range(start, stop)
print(my_nums)
# range(5, 10)

my_nums = list(range(start, stop))
print(my_nums)
# [5, 6, 7, 8, 9]

List Comprehension

nums = range(0, 10)
print([x**2 for x in nums if (x % 2 == 0)])
# [0, 4, 16, 36, 64]

# Omitting the conditional part
nums = range(0, 10)
print([x**2 for x in nums])
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# A practical example: Generate a random String with length 3
import random
import string

print(''.join([random.choice(string.ascii_lowercase) for _ in range(3)]))
# ujd

Slicing

my_list = list(range(0, 10))
print(my_list)
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

print(my_list[0:2])
# [0, 1]

print(my_list[:5])
# [0, 1, 2, 3, 4]

print(my_list[5:])
# [5, 6, 7, 8, 9]

Tuple

x = (1, 'a', 2, 'b')
print(type(x))
# <class 'tuple'>

Any sequence or an iterable can be converted to a tuple using the tuple() method.

tp = tuple(range(1,10))
print(tp)
# (1, 2, 3, 4, 5, 6, 7, 8, 9)
# A tuple of lists
tp = ([1,2], [3, 4])
print(tp)
# ([1, 2], [3, 4])

# Modifying an object in the tuple is possible:
tp[0].append(3)
print(tp)
# ([1, 2, 3], [3, 4])

# The following is not allowed:
# tp[2] = [5, 6]
# TypeError: 'tuple' object does not support item assignment

A sequence of values will also be treated as a tuple:

tp = 1, 2, 3
print(type(tp))
# <class 'tuple'>

Unpacking Values of a Tuple to Variables

tp = ('koray', 'deniz', 'toprak')
koray, deniz, toprak = tp
print(koray)
# koray

This feature can be used to return multiple values from a function:

def names():
    return ('koray', 'deniz', 'toprak')

koray, deniz, toprak = names()
print(koray)
# koray

Dictionary

x = {
    'foo': 'bar',
    'baz': 'qux'
}

print(type(x))
# <class 'dict'>

Set

my_set = {'foo', 'bar'}
print(type(my_set))
# <class 'set'>