payment by upi: sinhamit@icici or payment by bank account name: amit kumar sinha, account number: 2646728782 IFSC code: KKBK0005660 SWIFT: KKBKINBB

Please support if you like my work by payment through upi: sinhamit@icici or payment by bank

account name: Amit Kumar Sinha,
account number: 2646728782
IFSC code: KKBK0005660
SWIFT: KKBKINBB


Slicing Strings, Lists and Tuples   in Category: Python   by amit

🕙 Posted on 2023-08-05 at 07:10:14     Read in Hindi ...


List, Tuple, Dictionary & Slicing

    You should remember that strings and tuples are immutable data-types, that is, they are not changeable. You have learned in previous pages, about various string methods, concate­nation, etc. It means that any built-in function for example, len(), any of string methods, concate­nation applied on a string literal, or extraction of a single character (using [] square brackets just after the variable name, or string literal itself), doesn't change the original value.

    If you want to use the result/output of such operation, then you have to assign those expressions to some variable name. In the following example, no matter how many string methods are applied to the variable name, my_string, its value will not be changed, unless you assign a new value to it. The print() function only displays the result of evaluated expressions or statements within its parentheses.

Example 1

my_string = 'caMelcaSe stRing'
string1 = my_string.title()
string2 = my_string.capitalize()
string3 = my_string.upper()
string4 = my_string.lower()

print( my_string )   # Outputs the original string

    There is no concept of CONSTANTS in Python, unlike other programming languages. And, thus, you can notice that a variable name can be assigned with a value (data) or re-assigned to another value, but those values may be of string or tuple data-type (literals), and thus immutable. Python is much memory efficient, because it stores a particular value (data) at only one memory location.

    However, list and dictionary data-types are mutable (changeable), and much more flexible and therefore, lists and dictionaries are frequently used after strings in Python. You can see that the string data-type has much more methods than other data-types. The three data-types, strings, lists and tuples are indexed based sequence data-type. It means that like strings, each individual item/element in a list or a tuple can be accessed by placing index number (positive or negative) within square brackets (just after the variable name or the list literal or tuple literal, as the case may be).

Example 2

my_string = "Hello World"
my_list = [ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" ]
my_tuple = ( "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" )

print( my_string, len( my_string ), type( my_string ) )
print( my_list, len( my_list ), type( my_list ) )
print( my_tuple, len( my_tuple ), type( my_tuple ) )

print( my_string[-1], my_list[-1], my_tuple[-1] )   # Outputs d d d
print( my_string[ -len( my_string ) ], my_list[ -len( my_string ) ], my_tuple[ -len( my_string ) ] )   # Outputs H H H

Hello World 11 <class 'str'>
["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"] 11 <class 'list'>
("H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d") 11 <class 'tuple'>
d d d
H H H

    In the above example, you can see that length of each of these three variables, my_string, my_list and my_tuple is 11. There is a blank space inside each of these variables, which is also counted as a character (of my_string) or an item/element (of my_list and my_tuple). The value assigned to an item/element of a list or a tuple, can be of any data-types, such as boolean, integer, float, string, list, tuple, dictionary, set, etc.

    You should also note that an empty string (without any blank space within a pair of single/double quotes), an empty list, an empty tuple, etc. can be assigned to an item/element of either list, tuple, or dictionary. Dictionary is non-indexed (key:value pair) sequence data-type, and any item/element can be added, removed, or accessed through respective keys.

Example 3

my_string = ''
my_list = [ '' ]
my_tuple = ( '', )                              # Remember: a single item/element to be inserted must be followed by comma symbol.
my_dict = { 'empty': '' }               # a dictionary must have key: value pair
my_set = { '' }                                   # otherwise, it will be a set data-type

print( my_string, len( my_string ), type( my_string ) )
print( my_list, len( my_list ), type( my_list ) )
print( my_tuple, len( my_tuple ), type( my_tuple ) )
print( my_dict, len( my_dict ), type( my_dict ) )
print( my_set, len( my_set ), type( my_set ) )

 0 <class 'str'>
[''] 1 <class 'list'>
('',) 1 <class 'tuple'>
{'empty': ''} 1 <class 'dict'>
{''} 1 <class 'set'>

    In the above example, there is only one item/element in each of variables, my_list, my_tuple, my_dict, and my_set, though the value of that item/element is an empty string. To access an item/element from indexed sequence data-types (that is, strings, lists, tuples), the trick is described above.

    However, to access an item/element from a dictionary data-type, you have to write exact key's name, which may be integer or string data-type. Keys in a dictionary cannot be non-hashable data-types, such as list, dict, set, and bytearray (See Dictionary Manipulation page). Set is unordered collection of items/elements, therefore, you cannot get individual item. Set is totally different data-type.

Example 3 (continued)

# print( my_string[0] )   # there is no character in empty string literal
print( my_list[0], len( my_list[0] ), type( my_list[0] ) )
print( my_tuple[0], len( my_tuple[0] ), type( my_tuple[0] ) )
print( my_dict['empty'], len( my_dict['empty'] ), type( my_dict['empty'] ) )
# print( my_set[0], len( my_set[0] ) )   # Outputs TypeError: 'set' object is not subscriptable

 0 <class 'str'>
 0 <class 'str'>
 0 <class 'str'>

Slicing of STRINGs, LISTs, and TUPLEs

    Generally, slicing is done with two arguments (separated by colon symbol) within [] square brackets just after the variable name or string/list/tuple literals. However, syntax for slicing is as follows:

string_literal[start:stop:step]

list_literal[start:stop:step]

tuple_literal[start:stop:step]

    start is the starting index number (inclusive) of the string literal, list literal, or tuple literal. Similarly, stop is the index number (exclusive) of that literal or variable name, before which slicing is done. It means that when you write [1:4], slicing will be done from index number 1 to 3. The third argument, step is positions which will be iterated, that is, when step is 1 (by default), no character or item/element will be skipped (left behind). When step is 2, then one character or an item/element will be skipped (left behind), and so on... [See Example 5].

    start and stop arguments take only integer data value (positive or negative index number), but step argument takes only positive integer value. These three arguments are optional, and can be left blank before and after : (colon) symbol. When start is left blank, the index number is 0 (zero), and when stop is left blank, the slicing will be done upto end of string/list/tuple literal. When step argument is left blank, then no characters or items/elements will be skipped.

    In the following table, you can see that each character (of String data-type), or each item/element of a list or a tuple has been indexed with following numbers. Taking again the Example 2 (from the top), let's do some slicing in Python.

Hello World
012345678910
-11-10-9-8-7-6-5-4-3-2-1

Example 4

    You can also use negative index numbers for start and stop arguments.

my_string = "Hello World"
my_list = [ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" ]
my_tuple = ( "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" )

sliced_string = my_string[1:4]
sliced_list = my_list[1:4]
sliced_tuple = my_tuple[1:4]
print( sliced_string, type( sliced_string ) )   # Outputs ell <class 'str'>
print( sliced_list, type( sliced_list ) )   # Outputs ['e', 'l', 'l'] <class 'list'>
print( sliced_tuple, type( sliced_tuple ) )   # Outputs ('e', 'l', 'l') <class 'tuple'>

Example 5

    When two or more characters / items in a string/list/tuple literal are of same value (also, same data-type in case of list/tuple), it may be confusing which character or item is skipped, when the third argument, step is used. Therefore, numbers are used in example 5, to distinugish that second and fourth characters/items are skipped.

my_string = "123456789"   # this is a string data-type
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]   # this is list of nine items
my_tuple = (1, 2, 3, 4, 5, 6, 7, 8, 9)   # this is tuple of nine items

sliced_string = my_string[0:5:2]
sliced_list = my_list[0:5:2]
sliced_tuple = my_tuple[0:5:2]
print( sliced_string )   # Outputs 135
print( sliced_list )   # Outputs [1, 3, 5]
print( sliced_tuple )   # Outputs (1, 3, 5)

Example 6

    In the following example 6, the slice() built-in function is used with three arguments separated by , (comma) symbol to slice the string literal "Hello World", the list literal ["H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"], and the tuple literal ("H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d"). In below example, first 'l' letter (index number 2), first 'o' letter (index number 4) and 'W' letter (index number 6) are skipped when slice( 1, 8, 2 ) is applied on each literal.

my_string = "Hello World"
my_list = [ "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" ]
my_tuple = ( "H", "e", "l", "l", "o", " ", "W", "o", "r", "l", "d" )

sliced_string = my_string[slice(1,8,2)]
sliced_list = my_list[slice(1,8,2)]
sliced_tuple = my_tuple[slice(1,8,2)]
print( sliced_string, type( sliced_string ) )   # Outputs el o <class 'str'>
print( sliced_list, type( sliced_list ) )   # Outputs ['e', 'l', ' ', 'o'] <class 'list'>
print( sliced_tuple, type( sliced_tuple ) )   # Outputs ('e', 'l', ' ', 'o') <class 'tuple'>

print( help( slice ) )   # Few lines of slice() help documentation is shown below:

C:\xampp\htdocs\python2023>python new.py
Help on class slice in module builtins:

class slice(object)
  |   slice(stop)
  |   slice(start, stop[, step])
  |
  |   Create a slice object.   This is used for extended slicing (e.g. a[0:10:2]).
  |


Leave a Comment: