Python 2.7: Lists & Dictionaries

Lists

Lists are the same as arrays in other programming languages. List can be defined using assigment:

fruits = [“banana”, “apple”, “strawberry”]

and can be accessed by indices, similar to any other programming language:

# output: strawberry print fruits[2]

substitution of existing element

will replace apple with kiwi in fruits list

fruits[1] = “kiwi”

defining an empty list:

vegetables = []

appending items to the existing list:

vegetables.append(“cucumber”) vegetables.append(“eggplant”)

obtaining the length of the list, i.e. number of elements in the list:

print len(vegetables)

List slicing

You can extract certain chunks of the list, using “: " syntax. You have indicate from and to index, to represent the index range.

# output: cucumber, eggplant print vegetables[0:2]

output: apple, strawberry

print fruits[1:3]

animals = “catdogfrog” cat = animals[:3] # slicing elements until the third dog = animals[3:6] # slicing based on range frog = animals[6:] # slicing elements starting from 7th

Searching through the list

You can search through the list using .index(item).

fruits = [‘apple’, ‘kiwi’, ‘banana’, ‘peach’]

output: 1 - i.e. index of element kiwi

kiwi_index = fruits.index(‘kiwi’) print “Kiwi found at position %s” % kiwi_index

insert watermelon in the kiwi position, pushing everything down

fruits.insert(kiwi_index, ‘watermelon’)

output: apple, watermelon, kiwi, banana, peach

print fruits

Traversing through the list

You can traverse through the list using the for loop.

# output: 2,4,6,8,10 my_list = [1,2,3,4,5] for number in my_list: print 2 * number

my_list = [5,6,3,2,1] for i in range(0, len(my_list)): print my_list[i]

Remove specific item from the list:

furniture = [‘sofa’, ‘chair’, ‘table’, ‘bed’] furniture.remove(‘chair’)

output: sofa, table, bed

print furniture

Other list functions

# sorting array in ascending order

output: 1,2,3,5,8

my_list = [2,5,1,3,8] my_list.sort() print my_list

using .pop(index) - returns element from the list and removes it

furniture = [‘sofa’, ‘chair’, ‘table’, ‘bed’] item = furniture.pop(2)

output: table

print item

output: sofa, chair, bed

print furniture

# output: list of numbers from 2 to 8, excluding 8

output: 2,3,4,5,6,7

list = range(2, 8) print list

Joining lists

Lists can be joined using summation operator

n = [1,2,3] m = [7,4,5]

def join_lists(x, y): return x + y

output: 1,2,3,7,4,5

print join_lists(n, m)

Also list can be multiplied by a certain number and that it will join with itself several times

m = [“A”]

output: [“A”,“A”,“A”,“A”,“A”,“A”,“A”,“A”,“A”,“A”]

print m * 10

List elements can be “imploded” to a string with a specified separator using .join(list) function.

my_list = [“I”, “believe”, “I”, “can”, “fly”] joint_string = " “.join(my_list)

output: “I believe I can fly”

print joint_string

Casting list elements to other data types

my_list_int = [1,2,3]

will return the same array of int, but casted to str

my_list_str = map(str, my_list_int)

Check if number is a member of the list:

import random my_list = [] my_list.append(random.randint(0,10)) my_list.append(random.randint(0,10)) my_list.append(random.randint(0,10))

guess_number = int(raw_input(“Guess a number between 0 and 10: “))

if guess_number not in range(0,10): print “The number is even not between 0 and 10” else: if guess_number in my_list: print “Congratulations, you found the number!” else: print “Sorry, you missed it!” print " “.join(map(str, my_list))

Dictionaries

Dictionaries are similar to associative arrays. They consist of key-value pairs.

score = {“James”: 12, “Samantha”: 43, “Andre”: 81}

output: 12

print score[“James”]

In contrast to lists which are enclosed by [] brackes, dictionaries are enclosed by curly braces {}.

Elements can be appened to dictionaries using dictionary[key] assignment

score[“Kate”] = 34

output: 4

print len(score)

Removing items from the dictionary:

score[“Rene”] = 29

output: 5

print len(score)

del score[“Rene”]

output: 4

print len(score)

Traversing through the dictionary

# output: Price of apple is 32.5

output: Price of potato is 20

prices = {“potato”: 20, “apple”: 32.5} for key in prices: print “Price of %s is %s” % (key, prices[key])