Lists


In [1]:
list1 = ['apple', 'banana', 'orange']
list1


Out[1]:
['apple', 'banana', 'orange']

In [2]:
list2 = [7, 11, 13, 17, 19]
list2


Out[2]:
[7, 11, 13, 17, 19]

In [3]:
list3 = ['text', 23, 66, -1, [0, 1]]
list3


Out[3]:
['text', 23, 66, -1, [0, 1]]

In [4]:
empty = []
empty


Out[4]:
[]

In [5]:
list1[0]


Out[5]:
'apple'

In [6]:
list1[-1]


Out[6]:
'orange'

In [7]:
list1[-2]


Out[7]:
'banana'

In [8]:
'orange' in list1


Out[8]:
True

In [9]:
'pineapple' in list1


Out[9]:
False

In [10]:
0 in list3


Out[10]:
False

In [11]:
0 in list3[-1]


Out[11]:
True

In [12]:
None in empty


Out[12]:
False

In [13]:
66 in list3


Out[13]:
True

In [14]:
len(list2)


Out[14]:
5

In [15]:
len(list3)


Out[15]:
5

In [16]:
del list2[2]
list2


Out[16]:
[7, 11, 17, 19]

In [17]:
new_list = list1 + list2
new_list


Out[17]:
['apple', 'banana', 'orange', 7, 11, 17, 19]

In [18]:
new_list * 2


Out[18]:
['apple',
 'banana',
 'orange',
 7,
 11,
 17,
 19,
 'apple',
 'banana',
 'orange',
 7,
 11,
 17,
 19]

In [19]:
[new_list] * 3


Out[19]:
[['apple', 'banana', 'orange', 7, 11, 17, 19],
 ['apple', 'banana', 'orange', 7, 11, 17, 19],
 ['apple', 'banana', 'orange', 7, 11, 17, 19]]

In [20]:
list2


Out[20]:
[7, 11, 17, 19]

In [21]:
list2.append(23)
list2


Out[21]:
[7, 11, 17, 19, 23]

In [22]:
#list.insert(index, obj)

list2.insert(0, 5)
list2


Out[22]:
[5, 7, 11, 17, 19, 23]

In [23]:
list2.insert(6, 29)
list2


Out[23]:
[5, 7, 11, 17, 19, 23, 29]

In [24]:
list2.insert(len(list2), 101)
list2


Out[24]:
[5, 7, 11, 17, 19, 23, 29, 101]

In [25]:
list2.insert(-1, 999) #it doesn't insert in the last position! :/
list2


Out[25]:
[5, 7, 11, 17, 19, 23, 29, 999, 101]

In [26]:
list2.remove(999) #remove the item 999
list2


Out[26]:
[5, 7, 11, 17, 19, 23, 29, 101]

In [27]:
list2.remove(list2[-1]) #here removed the last one!
list2


Out[27]:
[5, 7, 11, 17, 19, 23, 29]

In [28]:
l1 = [1, 2]
l2 = [3, 4]
l1.extend(l2)
l1


Out[28]:
[1, 2, 3, 4]

In [29]:
l2


Out[29]:
[3, 4]

In [30]:
list_unsorted = [10, 3, 7, 12, 1, 20]
list_unsorted.sort()
list_unsorted


Out[30]:
[1, 3, 7, 10, 12, 20]

In [151]:
list_unsorted.sort(reverse = True) # L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
list_unsorted


Out[151]:
[20, 12, 10, 7, 3, 1]

In [31]:
l1


Out[31]:
[1, 2, 3, 4]

In [32]:
l2


Out[32]:
[3, 4]

In [33]:
l2 = l1.copy()

In [34]:
l2


Out[34]:
[1, 2, 3, 4]

In [35]:
l2 == l1


Out[35]:
True

In [36]:
id(l1)


Out[36]:
139959401512328

In [37]:
id(l2)


Out[37]:
139959401231048

In [38]:
# It's better use copy()! Look: 

l1 = ['a', 'b', 'c']
l2 = l1
l1


Out[38]:
['a', 'b', 'c']

In [39]:
l2


Out[39]:
['a', 'b', 'c']

In [40]:
l2.append('d')
l2


Out[40]:
['a', 'b', 'c', 'd']

In [41]:
l1


Out[41]:
['a', 'b', 'c', 'd']

In [42]:
l1 == l2


Out[42]:
True

In [43]:
id(l1)


Out[43]:
139959401232840

In [44]:
id(l2) # same id! watch it.


Out[44]:
139959401232840

In [45]:
# Slicing

list10 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list10[4:] #took the 4th and goes on


Out[45]:
[4, 5, 6, 7, 8, 9, 10]

In [46]:
list10[4:6] #list[start:end] #item starts through end-1


Out[46]:
[4, 5]

In [47]:
list10[-2:] # the last 2 items in the array


Out[47]:
[9, 10]

In [48]:
list10[:-2] # everthing except the last 2 items


Out[48]:
[0, 1, 2, 3, 4, 5, 6, 7, 8]

In [49]:
# sliceable[start:stop:step]
list10[::2] # os pares (pula de 2 em 2)


Out[49]:
[0, 2, 4, 6, 8, 10]

In [50]:
list10[1::2] # os ímpares


Out[50]:
[1, 3, 5, 7, 9]

In [51]:
# and if I wanna know the index position of an item?

list10


Out[51]:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

In [52]:
list10.index(6)


Out[52]:
6

In [54]:
list20 = [1, 2, 1, 3, 1, 4, 1, 5]
list20.count(1) # it counts the number of times the "1" appears in the list


Out[54]:
4

In [55]:
list20.count(4)


Out[55]:
1

In [56]:
list20.count(10)


Out[56]:
0

In [57]:
list20.pop()


Out[57]:
5

In [58]:
list20


Out[58]:
[1, 2, 1, 3, 1, 4, 1]

In [59]:
list20.sort(reverse=True)

In [60]:
list20


Out[60]:
[4, 3, 2, 1, 1, 1, 1]

In [127]:
max(list20)


Out[127]:
4

In [128]:
sum(list20)


Out[128]:
13

In [129]:
courses = ['History', 'Math', 'Physics', 'CompSci']

for index, course in enumerate(courses):
    print(index, course)


0 History
1 Math
2 Physics
3 CompSci

In [130]:
course_str = ', '.join(courses)
print(course_str)


History, Math, Physics, CompSci

In [131]:
new_list = course_str.split(', ')
new_list


Out[131]:
['History', 'Math', 'Physics', 'CompSci']

In [137]:
cs_courses = ['History', 'Math', 'Physics', 'CompSci']
art_courses = ['History', 'Math', 'Art', 'Design']

list(set(cs_courses) & set(art_courses))


Out[137]:
{'History', 'Math'}

In [138]:
set(cs_courses).intersection(art_courses)


Out[138]:
{'History', 'Math'}

In [140]:
set(cs_courses).difference(art_courses) # there's only in cs_courses


Out[140]:
{'CompSci', 'Physics'}

In [142]:
set(art_courses).difference(cs_courses) #there's only in art_courses


Out[142]:
{'Art', 'Design'}

In [143]:
set(cs_courses).union(art_courses) # the two lists together


Out[143]:
{'Art', 'CompSci', 'Design', 'History', 'Math', 'Physics'}

Unpacking


In [147]:
x = ['Patton', 'Zorn', 'Hancock']

a, b, c = x
a


Out[147]:
'Patton'

In [148]:
b, c


Out[148]:
('Zorn', 'Hancock')

List Comprehensions


In [61]:
# Examples from https://docs.python.org/3/tutorial/datastructures.html

squares = []

for x in range(10):
    squares.append(x ** 2)

squares


Out[61]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [62]:
squares2 = [x ** 2 for x in range(10)]

In [63]:
squares2


Out[63]:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

In [97]:
new_range = [i * i for i in range(5) if i % 2 == 0]
new_range


Out[97]:
[0, 4, 16]

A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses.


In [64]:
combs = []

for x in [1, 2, 3]:
    for y in [3, 1, 5]:
        if x != y:
            combs.append((x, y))

combs


Out[64]:
[(1, 3), (1, 5), (2, 3), (2, 1), (2, 5), (3, 1), (3, 5)]

In [65]:
# and in list comprehension format:

combs2 = [(x, y) for x in [1, 2, 3] for y in [3, 1, 5] if x != y]
combs2


Out[65]:
[(1, 3), (1, 5), (2, 3), (2, 1), (2, 5), (3, 1), (3, 5)]

In [66]:
combs == combs2


Out[66]:
True

In [67]:
vec = [-4, -2, 0, 2, 4]
[x*2 for x in vec]


Out[67]:
[-8, -4, 0, 4, 8]

In [68]:
# exclude negative numbers:

[x for x in vec if x >= 0]


Out[68]:
[0, 2, 4]

In [69]:
# absolute in all numbers:

[abs(x) for x in vec]


Out[69]:
[4, 2, 0, 2, 4]

In [70]:
freshfruit = ['   banana                ', 'passion fruit      ']
[weapon.strip() for weapon in freshfruit] # strip() removes the white spaces at the start and end, including spaces, tabs, newlines and carriage returns


Out[70]:
['banana', 'passion fruit']

In [71]:
# list of 2-tuples like (number, square)

[(y, y**2) for y in range(6)]


Out[71]:
[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25)]

In [72]:
# flatten a list using listcomp with two 'for'

vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[num for elem in vec for num in elem]


Out[72]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In [73]:
# in another words:

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

new_list = []

for elem in vec:
    for num in elem:
        new_list.append(num)

new_list


Out[73]:
[1, 2, 3, 4, 5, 6, 7, 8, 9]

In [74]:
from math import pi
[str(round(pi, i)) for i in range(1, 6)]


Out[74]:
['3.1', '3.14', '3.142', '3.1416', '3.14159']

In [75]:
# https://en.wikipedia.org/wiki/List_comprehension
s = {v for v in 'ABCDABCD' if v not in 'CB'}
print(s)


{'A', 'D'}

In [76]:
s


Out[76]:
{'A', 'D'}

In [77]:
type(s)


Out[77]:
set

In [87]:
s = {key: val for key, val in enumerate('ABCD') if val not in 'CB'}
s


Out[87]:
{0: 'A', 3: 'D'}

In [89]:
# regular list comprehension
a = [(x, y) for x in range(1, 6) for y in range(3, 6)]
a


Out[89]:
[(1, 3),
 (1, 4),
 (1, 5),
 (2, 3),
 (2, 4),
 (2, 5),
 (3, 3),
 (3, 4),
 (3, 5),
 (4, 3),
 (4, 4),
 (4, 5),
 (5, 3),
 (5, 4),
 (5, 5)]

In [91]:
# in another words:

b = []

for x in range(1, 6):
    for y in range(3, 6):
        b.append((x,y))
b


Out[91]:
[(1, 3),
 (1, 4),
 (1, 5),
 (2, 3),
 (2, 4),
 (2, 5),
 (3, 3),
 (3, 4),
 (3, 5),
 (4, 3),
 (4, 4),
 (4, 5),
 (5, 3),
 (5, 4),
 (5, 5)]

In [92]:
a == b


Out[92]:
True

In [95]:
# parallel/zipped list comprehension
c = [x for x in zip(range(1, 6), range(3, 6))]
c


Out[95]:
[(1, 3), (2, 4), (3, 5)]

In [100]:
# http://www.pythonforbeginners.com/basics/list-comprehensions-in-python
listOfWords = ['this', 'is', 'a', 'list', 'of', 'words']

[word[0] for word in listOfWords]


Out[100]:
['t', 'i', 'a', 'l', 'o', 'w']

In [103]:
# or...

listOfWords = ["this","is","a","list","of","words"]

items = [word[0] for word in listOfWords]

items


Out[103]:
['t', 'i', 'a', 'l', 'o', 'w']

In [104]:
[x.lower() for x in ['A', 'B', 'C']]


Out[104]:
['a', 'b', 'c']

In [105]:
[x.upper() for x in ['a', 'b', 'c']]


Out[105]:
['A', 'B', 'C']

In [106]:
string = 'Hello 12345 World'

numbers = [x for x in string if x.isdigit()]

numbers


Out[106]:
['1', '2', '3', '4', '5']

In [107]:
another_string = 'Hello 12345 World'

just_text = [x for x in another_string if x.isalpha()]

just_text


Out[107]:
['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']

In [108]:
just_text = [just_text[:5], just_text[5:]]
just_text


Out[108]:
[['H', 'e', 'l', 'l', 'o'], ['W', 'o', 'r', 'l', 'd']]

In [123]:
part1 = ''.join(just_text[0])
part1


Out[123]:
'Hello'

In [124]:
part2 = ''.join(just_text[1])
part2


Out[124]:
'World'

In [126]:
# finally...

just_text = [part1, part2]
just_text


Out[126]:
['Hello', 'World']

In [ ]: