Python Cheatsheet: Part III

Lists

my_list = [1,42,3,54,3,56,2]

Delete an element

# If you know the index
del my_list[0]

# Or you want to delete a slice
del my_list[2:4]
# if you want to delete the first occurrence
my_list.remove(3)

Concatenation

>>> list1 = [34, 65]
>>> list1 = list1 + [44, 77]
>>> print(list1)
[34, 65, 44, 77]

Add a list as an element

>>> list1 = list1 + [[44, 77]]
>>> print(list1)
[34, 65, 44, 77, [44, 77]]

Append

[34, 65, 44, 77, [44, 77]]
>>> list1.append(10)
>>> print(list1)
[34, 65, 44, 77, [44, 77], 10]

append(), remove() & insert() method returns None so never assign it to the original list. It happens because lists are mutable.

>>> list1 = list1.append(10)
>>> print(list1)
None

String to List

Only iterable types are allowed.

list_str = list("name")

Tuples

>>> t = 'A',23,True,10
>>> t
('A', 23, True, 10)

Multiple Assignments

Only iterable types

>>> A,B,C,D,E="hello"
>>> E
'o'

Written with StackEdit.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: