sajad torkamani

Arrays

Get index of element:

[2, 4, 6, 8].index(6)
# 2

Dictionaries

Check if key exists in dictionary

d = {"foo": 10, "bar": 23}

if "foo" in d:
    print("yaaaa")

Iterate over dictionary

people = { bob: 'Bob Doe', john: 'John Doe' }

for nickname, full_name in people.items():
  print("Nickname: {nickname}, Full name: {full_name}"

Lists

Map over list

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
capitalized_fruits = [fruit.upper() for fruit in fruits]

print(capitalized_fruits)
# ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']

Filter list

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even_nums = filter(lambda x: x % 2 == 0, nums)
odd_nums = filter(lambda x: x % 2 == 1, nums)

print(list(even_nums))
print(list(odd_nums))

(repl)

Type conversion

Convert number to string

str(10)
# '10'

Convert string to number

int('10')
# 10

Convert string into list of characters

list('sajad')
# ['s', 'a', 'j', 'a', 'd']

Types

Get type of variable

type(3)
# => <class 'int'>

Check type of variable

type(3) is int
type(3) is str
type(3) is float
Tagged: Python