Lists

– Remove duplicates from list

l = [1,2,3,1]
s = set(l)
l = list(s)
print l
----------------------------------------
[1, 2, 3]

– Merge lists

l1 = [1,2,3]
l2 = [4,5,6]
l3 = l1 + l2
print l3
----------------------------------------
[1, 2, 3, 4, 5, 6]

– Sort lists (in-place)

l = [3,2,4,5,1]
l.sort()
print l
----------------------------------------
[1, 2, 3, 4, 5]

– Sort lists (create a new list)

l = [3,2,4,5,1]
print sorted(l)
----------------------------------------
[1, 2, 3, 4, 5]

– Compare lists

l1 = [1,2,3]
l2 = [1,2,3]
l3 = [4,5,6]

if l1 == l2:
    print 'same'
else:
    print 'not same'

if l1 == l3:
    print 'same'
else:
    print 'not same'
----------------------------------------
same
not same

– Print all except certain items from list, 1 in our example

l = [1,2,3,4,1,1,1]
print [x for x in l if x != 1]
----------------------------------------
[2, 3, 4]

– Append to a list

l = [1,2,3,4,5,6,7]
l.append(8)
print l
----------------------------------------
[1, 2, 3, 4, 5, 6, 7, 8]

– Reverse a list

l = [1,2,3,4,5,6,7]
print l[::-1]
# OR
l.reverse()
print l1
----------------------------------------
[7, 6, 5, 4, 3, 2, 1]
[7, 6, 5, 4, 3, 2, 1]

– Extend list1 with list2

l1 = [1,2,3,4,5,6,7]
l2 = [8,9]
l1.extend(l2)
print l1
----------------------------------------
[1, 2, 3, 4, 5, 6, 7, 8, 9]

– Insert into a list

l1 = [1,2,3,4,5,6,7]
l1.insert(1,'a')
print l1
----------------------------------------
[1, 'a', 2, 3, 4, 5, 6, 7]

– Remove index # or if no index specified, last element of list and RETURN it

l1 = [1,2,3,4,5,6,7,'a']
l1.pop(6)
print l1
l1.pop()
----------------------------------------
[1, 2, 3, 4, 5, 6, 'a']
[1, 2, 3, 4, 5, 6]

– Remove the first occurence of an element

l1 = [1,2,3,4,5,6,7,'a','a']
l1.remove('a')
print l1
----------------------------------------
[1, 2, 3, 4, 5, 6, 7, 'a']

– Return index of specified element

l1 = [1,2,3,4,5,6,7,'a']
print l1.index(2)
----------------------------------------
1

– Return the number of times x appears in the list.

l1 = [1,2,3,4,2,2,2,5,6,7,'a']
print l1.count(2)
----------------------------------------
4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s