1.What will the following code output?
>>> word=’abcdefghij’
>>> word[:3]+word[3:]
The output is ‘abcdefghij’. The first slice gives us ‘abc’, the next gives us ‘defghij’.
2.How will you convert a list into a string?
We will use the join() method for this.
>>> nums=['one','two','three','four','five','six','seven']
>>> s=' '.join(nums)
>>> s
‘one two three four five six seven’
3. How will you remove a duplicate element from a list?
We can turn it into a set to do that.
>>> list=[1,2,1,3,4,2] >>> set(list) {1, 2, 3, 4}
4. Explain the //, %, and ** operators in Python.
The // operator performs floor division. It will return the integer part of the result on division.
>>> 7//2
3
Normal division would return 3.5 here.
Similarly, ** performs exponentiation. a**b returns the value of a raised to the power b.
>>> 2**10
1024
Finally, % is for modulus. This gives us the value left after the highest achievable division.
>>> 13%7 6
5. Explain identity operators in Python.
The operators ‘is’ and ‘is not’ tell us if two values have the same identity. 1.
>>> 10 is '10' False >>> True is not False True
6. What are numbers?
Python provides us with five kinds of data types:
Numbers – Numbers use to hold numerical values.
>>> a=7.0
7. What are Strings?
A string is a sequence of characters. We declare it using single or double
quotes.
>>> title="Ayushi's Book"
8. What are Lists?
Lists – A list is an ordered collection of values, and we declare it using square brackets.
>>> colors=['red','green','blue']
>>> type(colors)
<class ‘list’>
9. What are Tuples?
Tuples – A tuple, like a list, is an ordered collection of values. The difference. However, is that a tuple is immutable. This means that we cannot change a value in it.
>>> name=(‘Ayushi’,’Sharma’)
>>> name[0]=’Avery’
Traceback (most recent call last):
File “<pyshell#129>”, line 1, in <module>
name[0]=’Avery’
TypeError: ‘tuple’ object does not support item assignment
10. What are Disctionary?
Dictionary – A dictionary is a data structure that holds key-value pairs. We
declare it using curly braces.
>>> squares={1:1,2:4,3:9,4:16,5:25}
>>> type(squares)
<class ‘dict’> 1. >>> type({})
<class ‘dict’> We can also use a dictionary comprehension:
>>> squares={x:x**2 for x in range(1,6)}
>>> squares {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}