jmquintana79
3/26/2016 - 6:39 AM

Manage elements of python list

Manage elements of python list

# delete element of list by value
>>> a = ['a', 'b', 'c', 'd']
>>> a.remove('b')
>>> print a
['a', 'c', 'd']

# delete element of list by index
>>> a = ['a', 'b', 'c', 'd']
>>> del a[1]
>>> print a
['a', 'c', 'd']


# delete duplicate elements of list
>>> a = ['a', 'a', 'b', 'c', 'c']
>>> a = list(set(a))
>>> print a
['a', 'b', 'c']

# sort elements
>>> a = [3, 6, 8, 2, 78, 1, 23, 45, 9]
>>> sorted(a)
# [1, 2, 3, 6, 8, 9, 23, 45, 78]
# sort reverse
>>> sorted(a, reverse=True)
# [78, 45, 23, 9, 8, 6, 3, 2, 1]


# find element and get his index
import numpy as np

array = [1,2,1,3,4,5,1]
item = 1
np_array = np.array(array)    
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)

# filter list 1
list(np.where(np_array>item))

# filter list 2
[i for i in list if i.attribute > value]

# filter list 3
[value_when_true(i) if condition(i) else value_when_false(i) for i in list]

# create string from elements of list
my_list = ["Hello", "world"]
print "-".join(my_list)
# Produce: "Hello-world"