>> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li[1]"> >> li ['a', 'b', 'mpilgrim', 'z', 'example'] >>> li[1]" />
Easy Tutorial
❮ Ref Set Issuperset Python Func Number Radians ❯

Python List Common Operations

Python3 Examples

1. List Definition

Example

>>> li = ["a", "b", "mpilgrim", "z", "example"]
>>> li
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1]        
'b'

2. List Negative Indexing

Example

>>> li 
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[-1] 
'example'
>>> li[-3] 
'mpilgrim'
>>> li 
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li[1:3]  
['b', 'mpilgrim'] 
>>> li[1:-1] 
['b', 'mpilgrim', 'z'] 
>>> li[0:3]  
['a', 'b', 'mpilgrim']

3. Adding Elements to List

Example

>>> li 
['a', 'b', 'mpilgrim', 'z', 'example']
>>> li.append("new")
>>> li 
['a', 'b', 'mpilgrim', 'z', 'example', 'new']
>>> li.insert(2, "new")
>>> li 
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new']
>>> li.extend(["two", "elements"]) 
>>> li 
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']

4. Searching in List

Example

>>> li 
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.index("example")
5
>>> li.index("new")
2
>>> li.index("c")
Traceback (innermost last):
 File "<interactive input>", line 1, in ?
ValueError: list.index(x): x not in list
>>> "c" in li
False

5. Removing Elements from List

Example

>>> li 
['a', 'b', 'new', 'mpilgrim', 'z', 'example', 'new', 'two', 'elements']
>>> li.remove("z")  
>>> li 
['a', 'b', 'new', 'mpilgrim', 'example', 'new', 'two', 'elements']
>>> li.remove("new")    # Removes the first occurrence of a value
>>> li 
['a', 'b', 'mpilgrim', 'example', 'new', 'two', 'elements']    # The second 'new' is not removed
>>> li.remove("c")     # If the value is not found, Python raises an exception
Traceback (innermost last): 
 File "<interactive input>", line 1, in ? 
ValueError: list.remove(x): x not in list
>>> li.pop()      # pop does two things: removes the last element of the list and returns its value.
'elements'
>>> li 
['a', 'b', 'mpilgrim', 'example', 'new', 'two']

6. List Operators

Example

>>> li = ['a', 'b', 'mpilgrim']
>>> li = li + ['example', 'new']
>>> li 
['a', 'b', 'mpilgrim', 'example', 'new']
>>> li += ['two']         
>>> li 
['a', 'b', 'mpilgrim', 'example', 'new', 'two']
>>> li = [1, 2] * 3
>>> li 
[1, 2, 1, 2, 1, 2]

7. Joining List into a String Using join

Example


params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
";".join(["%s=%s" % (k, v) for k, v in params.items()])
'server=mpilgrim;uid=sa;database=master;pwd=secret'

join can only be used for lists where the elements are strings; it does not perform any type coercion. Concatenating a list that contains one or more non-string elements will raise an exception.

Splitting Strings with List

Example

li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
s
'server=mpilgrim;uid=sa;database=master;pwd=secret'
s.split(";")
['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s.split(";", 1)
['server=mpilgrim', 'uid=sa;database=master;pwd=secret']

split is the opposite of join, it splits a string into a multi-element list.

Note that the delimiter (";") is completely removed; it does not appear in any of the elements of the returned list.

split accepts an optional second parameter, which is the number of times to split.

Mapping Comprehension of List

Example

li = [1, 9, 8, 4]
[elem*2 for elem in li]
[2, 18, 16, 8]
li
[1, 9, 8, 4]
li = [elem*2 for elem in li]
li
[2, 18, 16, 8]

Comprehension in Dictionary

Example

params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
params.keys()
dict_keys(['server', 'database', 'uid', 'pwd'])
params.values()
dict_values(['mpilgrim', 'master', 'sa', 'secret'])
params.items()
dict_items([('server', 'mpilgrim'), ('database', 'master'), ('uid', 'sa'), ('pwd', 'secret')])
[k for k, v in params.items()]
['server', 'database', 'uid', 'pwd']
[v for k, v in params.items()]
['mpilgrim', 'master', 'sa', 'secret']
["%s=%s" % (k, v) for k, v in params.items()]
['server=mpilgrim', 'database=master', 'uid=sa', 'pwd=secret']

Filtering List

Example

li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
[elem for elem in li if len(elem) > 1]
['mpilgrim', 'foo']
[elem for elem in li if elem != "b"]
['a', 'mpilgrim', 'foo', 'c', 'd', 'd']
[elem for elem in li if li.count(elem) == 1]
['a', 'mpilgrim', 'foo', 'c']

Python3 Examples

❮ Ref Set Issuperset Python Func Number Radians ❯