Diff between C and Python
Diff between C and Python
String
A string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Strings can be created using
either single („) or double (“) quotes. In Python, it is not possible to delete individual characters from a string since strings are immutable(once an object is
created, its value cannot be changed).
s1 = 'GfG'
print(s1) o/p: GfG
If we need a string to span multiple lines then we can use triple quotes (”‟ or “””).
s = """I am Learning
Python String on GeeksforGeeks"""
print(s)
o/p: I am Learning
Python String on GeeksforGeeks
Slicing is a way to extract portion of a string by specifying the start and end indexes. The syntax for slicing is string[start:end], where start starting index
and end is stopping index (excluded).
s = "GeeksforGeeks"
print(s[1:4]) o/p: eek
len(): The len() function returns the total number of characters in a string.
s = "GeeksforGeeks"
print(len(s)) output: 13
List
a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain
mixed type of items. List is a Mutable. Hence, we can modify, replace or delete the items.
* List can contain duplicate items; * List are ordered. It maintain the order of elements based on how they are added.
* Accessing items in List can be done directly using their position (index), starting from 0.
Creating a Python list with different data types
a = [10, 2.10, "GfG", True]
print(a) o/p: [10, 2.10, GfG, True]
Elements in a list can be accessed using indexing. Python indexes start at 0, so a[0] will access the first element, while negative indexing allows us to access
elements from the end of the list. Like index -1 represents the last elements of list.
a = [10, 20, 30, 40, 50]
# Access first element
print(a[0]) o/p: 10
# Access last element
print(a[-1]) o/p: 50
Adding Elements into List
We can add elements to a list using the following methods:
append(): Adds an element at the end of the list; extend(): Adds multiple elements to the end of the list; insert(): Adds an element at a specific position.
# Initialize an list
a = [2]
We can change (bcz mutable) the value of an element by accessing it using its index.
a = [10, 20, 30, 40, 50]
# Change the second element
a[1] = 25
print(a) o/p: [10, 25, 30, 40, 50]
Tuple
A tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e.,
they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogeneous and immutable.
Using String
tup = ('Geeks', 'For')
print(tup) o/p: ('Geeks', 'For')
# Using List
list = [1, 2, 4, 5, 6]
print(tuple(list)) o/p: (1, 2, 4, 5, 6)
We can access the elements of a tuple by using indexing and slicing, similar to how we access elements in a list. Indexing starts at 0 for the first element and
goes up to n-1, where n is the number of elements in the tuple. Negative indexing starts from -1 for the last element and goes backward.
Slicing a tuple means creating a new tuple from a subset of elements of the original tuple. The slicing syntax is tuple[start:stop].
Slicing of a Tuple with Numbers
tup = tuple('GEEKSFORGEEKS')
Printing elements of a Range
print(tup[4:9]) o/p: ('S', 'F', 'O', 'R', 'G')
Since tuples are immutable, we cannot delete individual elements of a tuple.
Dictionary
dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can’t be
repeated and must be immutable. A dictionary can be created by placing a sequence of elements within curly { } braces, separated by a ‘comma’.
Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to find values.
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d) o/p: {1: 'Geeks', 2: 'For', 3: 'Geeks'}
Set
Set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of
elements in a set is not preserved and can change the most basic and efficient method for creating a set is using curly braces.
Example:
set1 = {1, 2, 3, 4}
print(set1) o/p: {1, 2, 3, 4}
We can add items to a set using add() and update(). add() method can be used to add only a single item. To add multiple items we use update() method.
Creating a set
set1 = {1, 2, 3}
Add multiple items
set1.update([5, 6])
print(set1) o/p: {1, 2, 3, 4, 5, 6}
We can remove an element from a set in Python using several methods: remove(), discard() and pop(). The remove() or discard() is used to remove a specified
element from the set. pop() method removes and returns an arbitrary element from the set. This means we don’t know which element will be removed. If the set
is empty, it raises a KeyError. clear() method removes all elements from the set, leaving it empty.
Arrays
In Python, array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. Unlike Python
lists (can store elements of mixed types), arrays must have all elements of same type. Having only homogeneous elements makes it memory-efficient.
In order to access the array items refer to the index number. Use the index operator [ ] to access an item in a array in Python. Elements can be removed from the
Python array by using built-in remove() function. It will raise an Error if element doesn’t exist. Remove() method only removes the first occurrence of the
searched element. To remove range of elements, we can use an iterator.
pop() function can also be used to remove and return an element from the array. By default it removes only the last element of the array. To remove element from
a specific position, index of that item is passed as an argument to pop() method.
Slicing of an Array
* Elements from beginning to a range use [:Index]; * Elements from end use [:-Index]; * Elements from specific Index till the end use [Index:]
* Elements within a range, use [Start Index:End Index]; * Print complete List, use [:]; * For Reverse list, use [::-1]
In order to update an element in the array we simply reassign a new value to the desired index we want to update.
Feature String List Tuple Dictionary
Mutable Immutable Mutable Immutable Mutable
Syntax "text" or 'text' [1, 2, 3] (1, 2, 3) {'key': 'value'}
Ordered Ordered Ordered Ordered Ordered (Python 3.7+)
Indexing Supports indexing Supports indexing Supports indexing No indexing (uses keys)
Duplicate Elements Allowed Allowed Allowed Keys are unique, values can duplicate
Use Case Text data Collection of items (mutable) Collection of items (immutable) Key-value pairs (mapping)
Example s = "hello" l = [1, 2, 3] t = (1, 2, 3) d = {'name': 'Alice', 'age': 25}
Methods upper(), lower(), split() append(), remove(), sort() count(), index() keys(), values(), items()
Memory Efficiency High Low High Low
Nesting Can be nested Can be nested Can be nested Can be nested
Performance Fast for text operations Slower for large datasets Faster than lists for iteration Fast for key-based lookups
1. Mutability:
o Strings and tuples are immutable (cannot be changed after creation).
o Lists and dictionaries are mutable (can be modified).
2. Order:
o Strings, lists, and tuples are ordered collections.
o Dictionaries are ordered in Python 3.7+ but are primarily used for key-value pairs.
3. Indexing:
o Strings, lists, and tuples support indexing.
o Dictionaries use keys to access values, not indexing.
4. Use Case:
o Strings are for text data.
o Lists are for mutable collections of items.
o Tuples are for immutable collections of items.
o Dictionaries are for key-value mappings.
5. Performance:
o Tuples are faster and more memory-efficient than lists.
o Dictionaries are optimized for fast key-based lookups.