Data Structuresand Algorithms Good OldJava AdvancedInterview Topics Cloud andDatabases Web Designand Development Must-knowTools Good ToKnow

## String, Set and Map in Python

String examples
```
foo = "Prismo Skills"

print (
str(len (foo)) + "\n" +
str(foo.index("Skill")) + "\n" +
foo.upper() + "\n" +
foo.lower() + "\n" +
foo[1:3] + "\n" +
str(foo.startswith("Hello")) + "\n" +
str(foo.endswith("Skills"))
)

```
Output:
```13
7
PRISMO SKILLS
prismo skills
ri
False
True
```

Set examples: Set in Python can only hold immutable keys.
```
>>> lst = [ 1, 'two', 3, 1, 'two' ]
>>> s = set(lst)
{1, 3, 'two'}

{1, 3, 4, 'two'}

>>> s.remove(4)
{1, 3, 'two'}

>>> 2 in s
False

>>> 'two' in s
True

>>> s2 = set([1,2,3])
{1, 2, 3}

>>> s - s2
{'two'}

>>> s & s2
{1, 3}

>>> s | s2
{1, 2, 3, 'two'}

# Sets in Python allow only immutable objects as keys.
# Immutable objects like lists cannot be added to a set.
>>> lst = [ 1, 'two', 3, 1, "two", [a,b,c], [a,b,c] ]
>>> s = set(lst)
# Traceback (most recent call last):
# TypeError: unhashable type: 'list'

# Tuples being immutable can be added to a set
>>> tple = (10,20,30)
{1, 3, (10, 20, 30), 'two'}

```

Map examples: Just like set, maps can also have only immutable keys
```
>>> m = {'one':1, 'two':[1,2,3], 3:3}
{'two': [1, 2, 3], 'one': 1, 3: 3}

>>> del m[3]
{'two': [1, 2, 3], 'one': 1}

>>> m[3] = 'three'
>>> m[('hello','world')] = ('hi','world')
{3: 'three', 'two': [1, 2, 3], 'one': 1, ('hello', 'world'): ('hi', 'world')}

>>> lst = [1,2,3]
>>> m[lst] = lst
# Traceback (most recent call last):
# TypeError: unhashable type: 'list'

>>> m.keys()
dict_keys([3, 'two', 'one', ('hello', 'world')])

>>> m.values()
dict_values(['three', [1, 2, 3], 1, ('hi', 'world')])

>>> m.items()
dict_items([(3, 'three'), ('two', [1, 2, 3]), ('one', 1), (('hello', 'world'), ('hi', 'world'))])

```

Like us on Facebook to remain in touch
with the latest in technology and tutorials!

Got a thought to share or found a
bug in the code?
We'd love to hear from you:

 Name: Email: (Your email is not shared with anybody) Comment: