Learn Python: Strings, Lists, Sets, Tuples and Dictionary

In this section we will learn about Strings , Lists, Sets, Tuples and Dictionary operators in detail and their basic usage in programming with the built in functions.

Learn Python: Strings,  Lists,  Sets, Tuples and Dictionary
python programming

Strings

Strings in Python work differently from those in other scripting languages. Python strings operate in the same basic function as C character arrays, a string is a sequence of single characters.

string = 'Hello World'

string = 'Hi there! You are looking great today!"

Note the two formats here, there is no difference within Python between using single or double quotes in string constants. By allowing both formats, you can include single quotes in double-quoted constants and double quotes in single quoted constants. Python also supports triple-quoted blocks. You can also use three single or double quotes, but make sure that you use the same number of quotes to start and terminate the constant.

Putting more than one quoted constantly on a line results in the constants being concatenated, such that

string = 'I' "love" "coding"
print(string)

Output: Ilovecoding

You can also concatenate string objects and constants using the "+" operator, just as you would with numbers:

greeting = 'hello'
name = 'python'
print(greeting+name)

output: hellopython

However, that you cannot concatenate strings with other objects. The expression

print('Python'+5)

raises an exception because the number object is not automatically translated to a string. Strings can also be multiplied using the * operator.

print('Python'*5)

output: PythonPythonPythonPythonPython

And finally, Python provides the built-in len a function that returns the number of characters in a string.

len('I am the walrus')

returns the value 15.

The len, the function actually calculates the length of any object that has a size (lists, dictionaries, etc.,.)

Strings are just Arrays

Strings are sequences, this means that you can access the individual characters in a string using array notation and you can access strings as if they were lists. The array notation for a string follows the same basic format as for other languages you append square brackets to the variable name, such that:

string = 'I returned a bag of groceries'
print(string[0])

output: I

Like C, the offset starts at 0 as the first character or element of the string. But unlike C, the indexing also follows you to specify a range, called slicing and Python is able to determine the position in the string from the end, rather than the beginning of the string.

string = 'I returned a bag of groceries'
print(string[0])
print(string[2:10])
print(string[-1])
print(string[13:])
print(string[-9:])
print(string[:-9])

create the following output:
I
returned
s
bag of groceries
I returned a bag of




The format of slicing is:

string[start:end]

The process of indexing and slicing use the following rules:

  • The returned string contains all of the characters starting from start up until but not including end.
  • If the start is specified but the end is not, the slice continues until the end of the string.
  • If the end is specified but the start is not, the slice starts from 0 up to but not including end.
  • If either start or end is specified as a negative number, the index specification is taken from the end, rather than from the start of the string where -1 is the latest character.

This rule makes more sense below

print(string[0])

prints the first character,

print(string[2:10])

prints character 3 through 9,

print(string[-1])

prints the last character,

print(string[13:]

print all of the characters after the fourteenth character,

print(string[-9:]

print the last nine characters, and 

print(string[:-9])

prints everything except for the last nine characters.

Although Python allows you to perform slices and other operations on strings, you must remember that strings are immutable sequences, they cannot change the place. Therefore the statement

string[:-9] = 'toffees'

It raises an exception, the only way to change the contents of a string is to actually make a new one. This means that for apparently simple operations such as the one just attempted

newstring =  string[:-9] + toffees
string = newstring

There are, of course, easier ways to change the contents of a string. One way is to use a function supplied in an external module (string) to do the work for us. The other way is to use string formatting, which is discussed in the next section.

Formatting

The % operator in Python allows you to format strings and other objects using the same basic notation as supported by the sprintf function in C. Because you are using an operator and not a function the usage is slightly different. You put the format string on the left of the % operator, and the object (or the tuple of objects) that you want interpolating into the returned expression on the right. For example, the statement

'And the sum was $%d, %s' % (1, 'which wasn't nice')
returns
And the sum was $1, which wasn't nice

The return value is always a string. The % operator accepts the same list of options as the C sprintf function.

Format Result
%% A percent sign.
%c A character with the given ASCII code
%s A string
%d A signed integer (decimal)
%u An unsigned integer (decimal)
%o An unsigned integer (octal)
%x An unsigned integer (hexadecimal)
%X An unsigned integer (hexadecimal using uppercase characters)
%e A floating-point number (scientific notation)
%E A floating-point number (scientific notation using E in place of e)
%f

A floating-point number (fixed decimal notation)

%g A floating-point number (%e of %f notation according to value size)
%G A floating-point number (as %g, but using E in place of e)
%p A pointer (prints the memory location of the value)
%n Stores the number of characters output so far into the next variable in the parameter list

Lists

Lists are another form of sequence object and therefore they inherit many of the operational parameters of the string, after all, a string is just a list of characters. However, unlike strings, Python lists can contain a list of any objects. You can store numbers, strings, other lists, dictionaries, and indeed any other object type that you can create within a list and even within the same list. Because it is a list of objects and because all Python data is stored as an object, the list can be made up of any combination of information you choose.

Using Lists

Python creates a list when you enclose a series of objects or constants within a pair of square brackets, as in the following statements:

list = [1, 2, 3, 4]
songs = ['I should be allowed to think', 'My heart goes on', 'Breathless']

The use of square brackets automatically implies an lists of objects.

hex = [[0, 1, 2, 3, 4, 5], [A, B, c, d, e, F, g]]

Like strings, lists are referenced according to the index of the item you are looking for, indexes start at 0. You can also concatenate the lists by using the + operator, which works in the same fashion as with string and numeric objects. In addition you can use augmented addition assignment to add items to the list, but you must specify a list as the object to be added, as in the following example.

>>> songs += ['AKA Driver']

Finally, you can multiply lists by a numeric object to repeat the elements within a list:

>>> list*2
output: [0, 1, 2, 3, 0, 1, 2, 3]

Note that you cannot multiply a list by a list, not that it would make much sense if you could!, However you can create a new list based on a simple expression. For example, given the list

>>> list = [1, 2, 3, 4]

If you want a list of the cubes of each element, you could use the map function in combination with an anonymous lambda function.

>>> cubes =  map(lambda(x) : x**3, list)

With Python 2.0 onwards, you can simply rewrite the preceding statement as follows:

>>> cubes = [x**3 for x in list]

Lists are Mutable

Remember how we said that strings were immutable objects but lists were mutable? Well the significance is that you can modify a list in place. With a string, the following operations raise an exception.

string = 'Narrow your eyes'
string[7:11] = 'her'

However, with a list, the following operation works
list = [0, 1, 2, 4, 16]
list[3:4] = [4,8]

And the result is a list with six elements, [0, 1, 2, 4, 8, 16]. Note that you have to specify a slice, if you tried using a list[3] in the second line in the preceding example, you'd replace the fourth element with an embedded two-element list. To delete items from the list, you need to use the del function, which accepts an element or slice from a list to be deleted such that:

del list[3]

deletes the fourth element and 

del list[1:4]

deletes the middle three elements from the list.

List Methods

Methods are special functions that are part of the object type definition. Methods are infact just functions that happens to be a specific to a particular type of object. Lists support a number of default methods that control the list contents. To use a method, you must specify the method with an object name, for example, to call the sort method.

numbers = [3, 5, 2, 0, 4]

numbers.sort()

In the above example if you want to print the sorted list, see the example below

print(numbers.sort())

output:None

numbers.sort()

instead you should do it in two lines:
print(numbers)

output: [0, 2, 3, 4, 5]
Method Description
append() Adds an element at the end of the list
clear() Removes all the elements from the list
copy() Returns a copy of the list
count() Returns the number of elements with the specified value
extend() Add the elements of a list (or any iterable), to the end of the current list
index() Returns the index of the first element with the specified value
insert() Adds an element at the specified position
pop() Removes the element at the specified position
remove() Removes the first item with the specified value
reverse() Reverses the order of the list
sort() Sorts the list

Tuples

Tuples are identical to lists except for one detail: tuples are immutable. Unlike lists, which you can chop and change and modify as you like, a tuple is a non-modifiable list. Once you created a new tuple, it cannot be modified without making a new tuple. To create a tuple instead of a list, use parenthesis instead of square brackets when defining the tuple contents, as in the following example.

month = ('Jan', 'Feb', 'Mar', 'Oct', 'Nov', 'Dec')

The preceding is a very good example of why Python has tuples. Because they cannot modify, you can use them if you don't have to alter the data that you have stored. Note that if you try to modify the tuple, an exception is raised to notify you of the error. This can be useful during development and debugging because it helps spot instances where you are misusing an object type. The following are the examples of tuple use:

one = (1,)
four = (1, 2, 3, 4)
five = 1, 2, 3, 4, 5
nest = ('Python', ('A', 'B', 'C', 'D'), (0, 1, 2, 3, 4, 5))

The first and third lines in the preceding statements are important to understand. In the case of the first line, to create a one-element you must use the redundant looking comma, otherwise, the Python interpreter parses(1) as a constant expression, the inclusion of the comma forces Python to interpret the statement as a tuple. The third line shows tuple creation without parentheses. Python allows you to create a tuple without using parentheses in those situations where the lack of parentheses is not ambiguous.

Using Tuples

Tuples support the same basic operations as lists. You can index, slice, concatenate and repeat tuples just as you can lists. The len function also works since a tuple is a sequence. The only action that you cant perform is modifying the tuples. It is also worth noting that tuple operations return tuples. The statement

three = five[:3]

makes three a tuple, not a list. Below are few basic tuple operations. Let's say Tuple t = (1, 2, 3, 4, 5) and Tuple t1 = (6, 7, 8, 9) are declared.

Operator Description Example
Repetition The repetition operator enables the tuple elements to be repeated multiple times.
T1*2 = (1, 2, 3, 4, 5, 1, 2, 3, 4, 5)
Concatenation It concatenates the tuple mentioned on either side of the operator.
T1+T2 = (1, 2, 3, 4, 5, 6, 7, 8, 9)
Membership It returns true if a particular item exists in the tuple otherwise false
print (2 in T1) prints True.
Iteration The for loop is used to iterate over the tuple elements.
for i in T1: 
    print(i)
Output
1
2
3
4
5
Length It is used to get the length of the tuple.
len(T1) = 5

Below are the Python built-in Functions

SN Function Description
1 cmp(tuple1, tuple2) It compares two tuples and returns true if tuple1 is greater than tuple2 otherwise false.
2 len(tuple) It calculates the length of the tuple.
3 max(tuple) It returns the maximum element of the tuple
4 min(tuple) It returns the minimum element of the tuple.
5 tuple(seq) It converts the specified sequence to the tuple.

Dictionaries

A dictionary element is split into two parts, the key and the value. You access the value from the dictionary by specifying the key. Like other objects and constants, Pyhton uses a strict format when creating dictionaries:

Dict = {"Name": "Tom", "Age": 22}    

To access an entry you use the square brackets to define the index entry of the element you want to be returned, just as you do with the strings or lists. In the above example, the Dict, Name and Age are immutable objects. Let's have an example:

Employee = {"Name": "John", "Age": 29, "salary":25000,"Company":"GOOGLE"}    
print(type(Employee))    
print("printing Employee data....")    
print(Employee) 

output:
<class 'dict'>
Printing Employee data.... 
{'Name': 'John', 'Age': 29, 'salary': 25000, 'Company': 'GOOGLE'}

We already discussed that, to access the data in List and tuples we use indexing. Similarly here we use keys as keys are unique in the dictionary. However, the interpreter raises an exception if the specified key cannot be found. If you had specified a key, you would have added, rather than update the entry. The following example

monthdays[ 'Aug' ] = 29

introduces a new element in the dictionary. You can delete the entries in a dictionary using the del function. Dictionaries are not sequences, so concatenation and multiplication will not work, if you try them both operations will raise an exception.

Using Dictionaries

Although dictionaries appear to work just like lists, the two in fact very different. Dictionaries have no order like lists, the indexes(keys) must be unique. But there is no logical order to the keys in the dictionary. This means that a dictionary is not a sequence, you cannot access the entries in a dictionary sequentially in the same way you can access entries in a string, list or tuple.

Dictionary Methods

SN Method Description
1 dic.clear() It is used to delete all the items of the dictionary.
2 dict.copy() It returns a shallow copy of the dictionary.
3 dict.fromkeys(iterable, value = None, /) Create a new dictionary from the iterable with the values equal to value.
4 dict.get(key, default = "None") It is used to get the value specified for the passed key.
5 dict.has_key(key) It returns true if the dictionary contains the specified key.
6 dict.items() It returns all the key-value pairs as a tuple.
7 dict.keys() It returns all the keys of the dictionary.
8 dict.setdefault(key,default= "None") It is used to set the key to the default value if the key is not specified in the dictionary
9 dict.update(dict2) It updates the dictionary by adding the key-value pair of dict2 to this dictionary.
10 dict.values() It returns all the values of the dictionary.
11 len() It returns the lenght of the items
12 popItem() It remove the item from the dictionary
13 pop() It removes the specific element from the dictionary
14 count() It give the count with specified value
15 index() It gives the specified index value