Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Python Essentials/2 Python Data Containers (Lists, Tuples, Dict, strings).ipynb
3603 views
Kernel: Python 3 (ipykernel)

Python Data Containers

Lists

Lists are ordered collections of items, defined using square brackets [].

You can access, modify, and perform operations on lists.

a=["ashi",25,14.5] a[0] a[-1] len(a) a.append("ab")
a del a[-1]
a
['ashi', 25, 14.5]
# Example: List operations fruits = ["apple", "banana", "cherry"] # Modify elements fruits[1] = "blueberry" print("Updated fruits:", fruits) # Add elements fruits.append("orange") print("After adding:", fruits) # Remove elements fruits.remove("apple") print("After removing apple:", fruits)
Updated fruits: ['apple', 'blueberry', 'cherry'] After adding: ['apple', 'blueberry', 'cherry', 'orange'] After removing apple: ['blueberry', 'cherry', 'orange']
fruits.insert(2,"Kiwi")
fruits
['blueberry', 'cherry', 'Kiwi', 'orange']
fruits+fruits 3*fruits
['blueberry', 'cherry', 'Kiwi', 'orange', 'blueberry', 'cherry', 'Kiwi', 'orange', 'blueberry', 'cherry', 'Kiwi', 'orange']
a=[100,120,780] print("sum is actually concadination:", a+a) print("multiplication is actually repetation:",3*a)
sum is actually concadination: [100, 120, 780, 100, 120, 780] multiplication is actually repetation: [100, 120, 780, 100, 120, 780, 100, 120, 780]

Tuples

Tuples are ordered, immutable collections of items, defined using parentheses (). Once created, the elements of a tuple cannot be changed.

# Example: Tuples m = (1, 2, 3, 4, 5) print("Tuple:", m) # Access elements print("First element:", m[0]) print("Last element:", m[-1])
Tuple: (1, 2, 3, 4, 5) First element: 1 Last element: 5
m.append(9) ##please note: tupels are immutable
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[24], line 1 ----> 1 m.append(9) AttributeError: 'tuple' object has no attribute 'append'

Dictionaries

Dictionaries store data in key-value pairs, defined using curly braces {}. They are unordered, mutable, and indexed by keys.

# Example: Dictionaries person = {"name": "alley", "age": 25, "city": "New York"} print("Dictionary:", person) # Access values by key print("Name:", person["name"]) # Add new key-value pair person["email"] = "[email protected]" print("Updated dictionary:", person) # Modify a value person["age"] = 26 print("After updating age:", person)
Dictionary: {'name': 'alley', 'age': 25, 'city': 'New York'} Name: alley Updated dictionary: {'name': 'alley', 'age': 25, 'city': 'New York', 'email': '[email protected]'} After updating age: {'name': 'alley', 'age': 26, 'city': 'New York', 'email': '[email protected]'}
person["Gender"]="Female" person person.keys() person.values() del person['name']
person
{'age': 26, 'city': 'New York', 'email': '[email protected]', 'Gender': 'Female'}

Sets

Sets are unordered collections of unique elements, defined using curly braces {}. They are useful for mathematical operations like union, intersection, and difference.

# Example: Sets set1 = {1, 2, 3,3, 4,4} set2 = {13, 4, 5, 6} print("Set1:", set1) print("Set2:", set2)
Set1: {1, 2, 3, 4} Set2: {13, 4, 5, 6}
set1[0] # indexing not supported in Sets
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[41], line 1 ----> 1 set1[0] TypeError: 'set' object is not subscriptable
# Union print("Union:", set1 | set2) # Intersection print("Intersection:", set1 & set2) # Difference print("Difference (set1 - set2):", set1 - set2) # Symmetric Difference print("Symmetric Difference:", set1 ^ set2) ## all uncommon elements
Union: {1, 2, 3, 4, 5, 6, 13} Intersection: {4} Difference (set1 - set2): {1, 2, 3} Symmetric Difference: {1, 2, 3, 5, 6, 13}

Strings

Strings are sequences of characters enclosed in single or double quotes. They support slicing, concatenation, and many built-in methods.

# Example: Strings text = "Python Programming" s="1234" b="1234abc has " # Access characters print("First character:", text[0]) print("Last character:", text[-1]) # Slicing print("First 6 characters:", text[:6]) print("Last 6 characters:", text[-6:]) # String methods print("Uppercase:", text.upper()) print("Lowercase:", text.lower()) print("Replace:", text.replace("Python", "Java"))
First character: P Last character: g First 6 characters: Python Last 6 characters: amming Uppercase: PYTHON PROGRAMMING Lowercase: python programming Replace: Java Programming
#please note: strings are immutable #s.append("456") #del s[2] del s
--------------------------------------------------------------------------- NameError Traceback (most recent call last) Cell In[39], line 4 1 #please note: strings are immutable 2 #s.append("456") 3 #del s[2] ----> 4 del s 5 s NameError: name 's' is not defined

Hands-on Quick Practice

Try solving the following problems:

  1. Create a tuple of 5 numbers and print the second and fourth element.

  2. Make a dictionary for storing student info (name, age, grade) and print values.

  3. Use sets to find common elements between two lists.

  4. Write a program to check if a word exists in a given string.

  5. Convert a string to uppercase and count how many vowels it has.

# Write your practice code here