Вы находитесь на странице: 1из 29

Strings , Lists and Tuples

Strings
Strings
● A string is a sequence of characters
a string can be expressed using within single quotes or doubel quotes.
“hello” or ‘hello’
● You can access the characters one at a time using bracket operator.
name = “hello”
● name[0] will return ‘h’
● name[-1] will return ‘o’
– The number inside the bracket is called an index
– The value of the index has to be an integer.
● len(): a built in function which returns number of characters in a string.
– len(name) will return 5
String slices
● A segment of a string is called a slice.
>>> dept = ‘Information Technology’
>>> print dept[0:11]
Information
>>> print dept[12:22]
● The operator [n:m] returns the part of the string
from the “n th” charachter to “m th” character ,
including the first and excluding the last.
String slices
● If you omit the first index(before the colon) the slice starts
at the beginning of the string.
>>> college = “vasavi”
>>> print college[:2]
‘va’
● If you omit the last index(after the colon) the slice goes to
the end of the string.
Print college[1:]
‘asavi’
Strings are immutable
● Strings are immutable, i.e you can’t change an existing
string.
>>> greeting = ‘Hello, World!’
>>> greeting[0] = ‘B’
● The best you can do is create a new string which is that
is a variation on the original.
>>> greeting = ‘Hello, World!’
>>> new_greeting = ‘B’ + greeting[1:]
>>> print new_greeting
Strings methods
● upper()
● lower()
● find()
find(arg1,start_index,stopping_index)
String methods which return
boolean values
Lists
List
● Like a string, A list is a sequence of values.
● In a string, the values are characters.
● In a list, they can be any type.
● The values in the list are called elements or
sometimes items.
Creating a list
There are several ways to create a list
– Simplest is to enclose the elements in a square
brackets [ ]
● [10, 20, 30, 40, 50]
● [‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’]
– The elements of the list don’t have to be of same type.
● [‘ram’, ‘kumar’, 19, 5.3 , ‘m’, [9812387321, 7077132323]]
– A list within another list is nested
– A list that contains no elements is called as an empty
list.
● []
assigning list values to variables
● days = [‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’]
● emp_details = [‘ram’, ‘kumar’, 19, 5.3 , ‘m’, [9812387321, 7077132323]]

● marks = [33,44,55,66,77]
● empty = [ ]
Accessing elements of a list
● Syntax of accessing the elements of a list is the same as for
accessing the characters of a string.
● Use bracket operator to access the elements of a list
● The expresssion inside the bracket specifies the index. Indices start
from 0
● days = [‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’]
– print (days[0])
● emp_details = [‘ram’, ‘kumar’, 19, 5.3 , ‘m’, [9812387321, 7077132323]]
– age = emp_details[2]
– contact_info = emp_details[5]
Lists are mutable
● Unlike strings, lists are mutable
– emp_details = [‘ram’, ‘kumar’, 19, 5.3 , ‘m’, [9812387321, 7077132323]]
– emp_details[2] = 20
print(emp_details)
● You can think of a list as a relationship between indices and elements.
● This relationship is called mapping.
● Each index ‘maps to’ one of the elements.
● List indices work the same way as string indices
– Any integer expression can be used as an index.
– If you try to read or write an element that does not exist, you get an
IndexError.
– If an index has a negative value, it counts backwards from the end of the list.
in operator on lists
● The in operator also works on lists
– days = [‘sun’, ‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’]
● ‘sun’ in days will return True
● ‘may’ in days will return False
Traversing a list...reading
● Most common way to traverse a list is by using for loop
● days = [‘sun’, ‘mon’, ‘tues’, ‘wednes’, ‘thurs’, ‘fri’, 
‘satur’]
for day in days:
print(day)
● The above code works well if you only need to read the elements of a
list.
● A for loop over an empty list never executes the body:
for z in [ ]:
print(‘This never happens’)
● A list can contain another list, the nested list still counts as a single element.
emp_details = [‘ram’, ‘kumar’, 19, 5.3 , ‘m’, [9812387321, 7077132323]]
– The length of the above list is 6
Traversing a list...read, write/update
● If you want to write or update the elements, you need the indices.
● A common way to do this is to combine the functions range and len:
for i in range(len(days)):
days[i] = days[i] + ‘day’
● len returns the number of elements in the list.
● range returns a list of indices from 0 to n­1, where n is length of the
list.
● Each time through the loop i gets the index of the next element.
● The assignment statement in the body uses i to read the old value of
the element and assign the new value.
List Operations
● The + operator concatenates lists:
bowlers = [‘shami’, ‘chanal’]
batsmen = [‘raina’, ‘gambhir’, ‘kohli’, ‘rahane’]
all_rounders = [‘ashwin’, ‘jadeja’, ‘pathan’]
wkt_keepers = [‘dhoni’, ‘karthik’]
cricket_team = bowlers + batsmen + all_rounders + 
wkt_keepers
List Operations

The * operator repeats a list a given number of times:
marks = [0]
marks = marks * 4

The above example repeats [0] four times.


clock = [‘tik’, ‘tok’]
print(clock * 3)

The above example repeats [‘tik’, ‘tok’] three


times.
List Slices
● Slice operator also works on lists
months = [‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’,
‘dec’]
months[ :4]
[‘jan’, ‘feb’, ‘mar’, ‘apr’]
if you omit the first index, the slice start at the beginning
months[5: ]
[‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’, ‘dec’]
if you omit the second, the slice goes to the end
months[:]
[‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’, ‘dec’]
if you omit both, the slice is a copy of whole list
months[3:6]
[‘apr’, ‘may’, ‘jun’]
List Slices...
● A slice operator on a left side of an assignment can update multiple
elements:
months = [‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’,
‘dec’]
months[0:2] = [‘january’, february’]
[‘january’, ‘february’, ‘mar’, ‘apr’, ‘may’, ‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’,
‘dec’]
List methods
append() : adds a new element to the end of the list
months = [‘jan’, ‘feb’, ‘mar’, ‘apr’, ‘may’, ‘jun’, ‘jul’, ‘aug’, ‘sep’, ‘oct’, ‘nov’]
months.append(‘dec’)
extend() : takes a list as an agrument and appends all of the elements
weekdays = [‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’]
weekends = [‘sat’, ‘sun’]
weekdays.extend(weekends)
[‘mon’, ‘tue’, ‘wed’, ‘thu’, ‘fri’, ‘sat’, ‘sun’]
sort() : arranges the elements of the list from low to high (ascending)
cities = [‘hyderabad’, ‘haryana’, ‘amritsar’, ‘delhi’, ‘mumbai’, ‘chennai’]
cities.sort()
● List methods are all void ; they modify the list and return None. If you
accidentally write
cities = cities.sort()
Deleting elements
pop() method can be used to delete element by index. It modifies the list and returs
the element that was deleted.
courses = [‘maths’, ‘physics’, ‘chemistry’, ‘biology’]
first_course = courses.pop(0)
print(courses)
print(first_course)
[‘physics’, ‘chemistry’, ‘biology’]
maths
If you don’t provide an index, it deletes and returns the last element.
courses = [‘maths’, ‘physics’, ‘chemistry’, ‘biology’]
last_element = courses.pop()
print(courses)
print(last_element)
[‘maths’, ‘physics’, ‘chemistry’]
biology
Deleting elements
* If you don’t need the removed value, you can use the del operator
courses = [‘maths’, ‘physics’, ‘chemistry’, ‘biology’]
del courses[1]
[‘maths’, ‘chemistry’, ‘biology’]
* To remove more than one element , you can use del with a slice index:
courses = [‘maths’, ‘physics’, ‘chemistry’, ‘biology’]
del courses[1:3]
[‘maths’, ‘biology’]
* If you know the element you want to remove (but not the index) , you can
use remove method
courses = [‘maths’, ‘physics’, ‘chemistry’, ‘biology’]
courses.remove(‘maths’)
[ ‘physics’, ‘chemistry’, ‘biology’]
Lists and strings
* A string is a sequence of charcters
* A list is a sequence of values
* But a list of characters is not same as a string
* To covert from a string to a list of characters , use list function
name = ‘vasavi’
aname = list(name)
print(aname)
[‘v’, ‘a’, ‘s’, ‘a’, ‘v’, ‘i’]
* If you want to break a string into words , use split method
college = ‘vasavi engineering college’
acollege = college.split()
print(acollege)
[‘vasavi’, ‘engineering’, ‘college’]
String delimiter and join
● An optional argument to the split method is called as a delimiter.
● A delimiter specifies which characters to use as word boundaries.
● E.g hyphen as a delimiter
roll_number = ‘1602-15-737-007’
delimiter = ‘-’
roll = roll_number.split(delimiter)
print(roll)
● Join is the inverse of split. It takes a list of strings and concatenates the
elements.
● Join is a string method, so you have to invoke it on delimiter and pass the
list as a parameter
delimiter = ‘-’
rolls = delimiter.join(roll)
Tuple
● A tuple is a sequence of values.
● The values can be any type and they are
indexed by integers.
● Tuples are immutable.
● Tuples are similar to lists, except that they are
immutable.
Creating a tuple
● Syntactically , a tuple is a comma seperated list of values
– days = 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'
● Although it is not necessary, it is common to enclose tuples in
parentheses:
– emp_details = ('ram', 'kumar', 19, 5.3, 'm', (9812387321, 7077132323))
● Using built-in function to create a tuple
– empty = tuple()
● To create a tuple with a single element, you have to include a
final comma:
– t2 = ‘a’,
Tuples
● As tuples are immutable methods like
pop, remove wont work
● Operations like del wont work
● Modification of any element of tuple wont work

Вам также может понравиться