0% found this document useful (0 votes)
233 views6 pages

Telusko Python Tutorial Overview

This document provides an overview of variables, strings, lists, tuples, and sets in Python. It explains how to create and manipulate these data types, including operations like slicing, concatenation, and using built-in functions. The document emphasizes the differences between mutable and immutable types, as well as the unique properties of sets and tuples.

Uploaded by

ajk952626
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
233 views6 pages

Telusko Python Tutorial Overview

This document provides an overview of variables, strings, lists, tuples, and sets in Python. It explains how to create and manipulate these data types, including operations like slicing, concatenation, and using built-in functions. The document emphasizes the differences between mutable and immutable types, as well as the unique properties of sets and tuples.

Uploaded by

ajk952626
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Variable

In this lecture we are discussing variable in python:


Variable: It is a container where we can put our value
e.g
>>x=2 #here x is variable and 2 is value
>>x+3
--5 **output
>>y=3

Note: If I want to use output of previous operation so we use underscore (_)

>> _+y
8 # previous output 5 and y is 3

Use String as a variable:


-- Strings in python are surrounded by either single quotation marks, or double quotation marks.
-- e.g "shiva" ,'shiva'

Assign String to a Variable:


-- Assigning a string to a variable is done with the variable name followed by an equal sign and the
string:
>>name='shiva'
>>name
shiva

Slicing String:
we can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.

-- Get the characters from position 2 to position 5 (not included):


>>name='youtube'
>>name[2:5]
'utu'

Slice From the Start:


>>name[:5] #from starting to index 5 (exclude)
'youtu'

Slice To the End:


>>name[2:] #from 2nd index to end
'utube'

Negative Indexing:

0 1 2 3 4 5 6 #positive indexing
y o u t u b e
-7 -6 -5 -4 -3 -2 -1 #Negative indexing

>>name[-1]
'e'

>>name[:-1]

Telusko python Page 1


>>name[:-1]
'youtub'

>>name[:]
'youtube'

>>name [:0]
''
>>name[-5:-2]
'utu'

Concatenate String:
>> name+ ' telusko'
'youtube telusko'

Telusko python Page 2


List

#1
Lists are used to store multiple items in a single variable.
- We have to use a square bracket [], and in that square bracket, we can store multiple values.
- We can print the list through the variable name.
- Lists are Mutable which means values can be changed in the list.
- We can also get the single value from the list using the index value.
- The index value is 1 less than the size of a list as the index value starts from 0.
e.g., If the size of the list is 5, then its index value lies in the range of 0 to 4.
- We can fetch only those values from a list that are in the range of index values of it.
- We can also get a sub-list of a list by using the slicing in a list.
- We can also fetch the value from a list through negative numbers similar to strings.
- A list of strings can also be created.
- We can also create a list that can store values of different data types.
Like it can store integer value, float value, string value etc, in a single list.
- A list of lists can also be created which means a list can also store different lists in it as well.

#2
- Several operations can also be performed using it and it has many in-built functions and methods
to use.
- nums. shows all the functions that are available with the list.
- Ctrl + Space can also be used to show the methods.
- append method is used to add a new value to the end of a list.
- clear will clear the entire list.
- insert method can add a value in between the list at the specified index.
- A particular element can also be deleted through the remove method.
- pop method will also remove the element through the index value and return that deleted
element as well.
- If you don't specify the index value in the pop method, it will delete and return the last element
from the list.
- del is a command through which you can delete a sub-list or multiple values from a list.
del list name[start:end]
- extend method is used to add multiple values or a sub-list in a list.
- sort method is used to get listed in the sorted order.
[Link]()

#3
- min() function is used to get the minimum value present in a list.
- max() function is used to get the maximum value of a list.
- sum() function returns the sum of all of the values present inside the list.

>>> nums = [25,12,36,95,14] >>> [Link](1)


>>> nums 12
[25, 12, 36, 95, 14] >>> nums
>>> nums[0] [25, 77, 36, 95, 45]
25 >>> [Link]()
>>> nums[4] 45
14 >>> del nums[2:]
>>> nums[2:] >>> nums

Telusko python Page 3


>>> nums[4] 45
14 >>> del nums[2:]
>>> nums[2:] >>> nums
[36, 95, 14] [25, 77]
>>> nums[-1] >>> [Link](29,12,14,36)
14 Traceback (most recent call last):
>>> nums[-5] File "<pyshell#25>", line 1, in <module>
25 [Link](29,12,14,36)
>>> names = ['navin','kiran','john'] TypeError: extend() takes exactly one argument (4 given)
>>> names >>> [Link]([29,12,14,36])
['navin', 'kiran', 'john'] >>> nums
>>> values = [9.5,'Navin',25] [25, 77, 29, 12, 14, 36]
>>> mil = [nums, names] >>> min(nums)
>>> mil 12
[[25, 12, 36, 95, 14], ['navin', 'kiran', 'john']] >>> max(nums)
>>> [Link](45) 77
>>> nums >>> sum(nums)
[25, 12, 36, 95, 14, 45] 193
>>> [Link]()
>>> nums
[12, 14, 25, 29, 36, 77]

Telusko python Page 4


Tuples And Set
In this lecture we will learn:
- What are Tuples in Python
- Tuples re immutable
- Methods used with tuples
- When to use tuples over lists?
- What are Sets in Python?
- Properties of Sets

#1
Tuples:-
Tuple is almost similar to a list in which we can store multiple values.
- Tuples are Immutable and we can change values in them.
- To define a tuple, () round brackets are used.
- We can fetch the values from a tuple using the index value that can be given in a square bracket.
- Tuple will give an error when you tried to change a value in it.

#2
- count method is used to count the occurrences of an element in a tuple. It counts the number of
times that an element is present in a tuple.
e.g., If an element of value 5 is present two times in a tuple, then the count method returns 2.

#3
- We can use tuples when we want a list of multiple values but we do not want to change it.
- Iteration in the tuple is faster than the list.

#4
Sets:-
- Set is a collection of unique elements.
- To define the set, we use the {} curly brackets.
- Set never follows the sequence.
- When we print the set, then the sequence of values in output will be different from the sequence
of input.
- Duplicate values present in a set will be printed only once in an output.
- Set uses the concept of Hash. Hash is used to improve the performance as it fetches the values as
fast as possible.
- Indexing is not supported in sets as it does not follow sequencing.
- Values can not be changed in a set also because index value is not supported.

>>> tup = (21,36,14,25)


>>> tup
(21, 36, 14, 25)
>>> tup[1]
36
>>> tup[1] = 33
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
tup[1] = 33
TypeError: 'tuple' object does not support item assignment
>>> s = {22,25,14,21,5}

Telusko python Page 5


>>> s = {22,25,14,21,5}
>>> s
{5, 14, 21, 22, 25}
>>> s = {25,14,98,63,75,98}
>>> s
{98, 75, 14, 25, 63}
>>> s[2]
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
s[2]
TypeError: 'set' object is not subscriptable
>>>

Telusko python Page 6

Common questions

Powered by AI

Immutability in tuples contributes to memory efficiency and improved performance in Python. Since tuples cannot be altered, Python can optimize their storage, sharing a tuple's memory location across different parts of the code without risk of concurrent modifications. This results in faster access times due to reduced overhead in memory management. Tuples' immutability also ensures that hash-based collections like sets and dictionaries can safely use them as keys, benefiting from consistent, unchanged state. Thus, immutability enhances performance by ensuring safe, efficient storage, and access patterns .

Tuples should be preferred over lists in scenarios where the data set is constant and should not be altered, as tuples are immutable. This immutability provides enhanced performance since iterations over tuples are faster compared to lists. Tuples also provide data integrity, ensuring that the values remain unchanged throughout the program, which is critical in cases where the data should remain read-only. Hence, for static collections where multiple values need to be stored and protected from accidental modification, tuples are highly advantageous .

Using lists to store different data types in Python enhances flexibility and functionality, allowing a single list to hold integers, floats, strings, or even other lists. This feature enables complex data structures, such as lists of lists, which support diverse data modeling needs and enable faster prototyping and experimentation. However, this flexibility comes with the trade-off of potential type-related errors during operations assuming uniform data types. Nonetheless, the heterogeneity of lists supports a dynamic programming paradigm, making Python more versatile for various applications and computational models .

Negative indexing in Python allows access to elements in a list or characters in a string starting from the end rather than the beginning. For instance, if a string is 'youtube', negative indexing can be used such that name[-1] returns the last character 'e'. Similarly, for lists, nums[-1] returns the last element of the list. The implications of using negative indexing in string manipulation include flexibility in traversing strings and lists from the end, which simplifies certain algorithms, especially when needing to reverse elements or when the position relative to the end of the sequence is known .

The count method in tuples is used to determine how many times a specific element appears, which is critical for examining frequency within sequences. An equivalent in lists, also called count, offers similar functionality, allowing frequency assessment of list elements. Sets do not support element counting directly due to their unique element constraint. The count method is useful in both tuples and lists for tasks like statistics gathering and data validation by providing insights into element distribution and occurrence frequency .

String slicing in Python can retrieve parts of the string based on start and end indexes. When slicing from the start, such as with name[:5] on the string 'youtube', it returns 'youtu' by extracting characters from index 0 to 4. When slicing to the end with name[2:], it yields 'utube', starting from index 2 to the last character. Using both indexes, like name[2:5], returns 'utu', extracting the substring from index 2 up to, but not including, index 5. This ability to specify start and end gives precise control over the part of the string being accessed .

Sets in Python are defined by their properties of holding unique elements, and they do not preserve any order. This unordered nature means that elements are not indexed, making some sequence operations, like getting an element by position, impossible. However, the unique element constraint means sets are ideal for deduplication tasks, ensuring that only one instance of each element is present. Sets also support operations like unions, intersections, and differences efficiently due to their underlying hash table implementation, which significantly speeds up element access and membership tests, enhancing data handling capabilities especially in scenarios requiring fast membership checks or deduplication .

The 'pop' method in Python lists removes and returns the element at a specified position. If no index is given, it removes and returns the last element, exemplified by nums.pop() returning and removing 45 from the list. Conversely, the 'remove' method deletes the first occurrence of a specified value without returning it. Therefore, 'pop' is useful when the element needs to be both removed and processed further, while 'remove' is more suitable for simply deleting an element by value, without regard for its position or further use of the deleted element .

The 'extend' method in Python lists is used to add multiple elements from an iterable (like another list) to the end of the current list. For example, nums.extend([29,12,14,36]) adds these numbers individually to the list. In contrast, 'append' adds its argument as a single element to the list, which can be used when the data to be added forms a single entity. One should use 'extend' when the goal is to merge another iterable's elements into the list rather than adding the iterable itself as a single element .

In Python, variables are essentially labels pointing to the objects stored in memory. When assigning an integer or string to a variable, like x=2 or name='shiva', Python binds the variable to that object. Reassigning the variable to another value redirects that label to a different object, leaving the original object available for garbage collection if no other references exist. This dynamic typing mechanism allows flexible and dynamic data manipulation, facilitating ease of programming and rapid development .

You might also like