Understanding Python's Core Data Structures
Strings (str)
Strings are among the most frequently used data types in Python. They can be created using single quotes ('), double quotes (") or triple quotes (''').
Creating a string is straightforward - simply assign a value to a variable.
message1 = 'Hello World!'
message2 = "Python Programming"
The syntax for string slicing is: variable[start_index:end_index]
text = 'Programming'
print(text) # Output the entire string
print(text[0:-1]) # Output from first to second-to-last character
print(text[0]) # Output the first character
print(text[2:5]) # Output from third to fifth character
print(text[2:]) # Output from third character to end
print(text * 2) # Output the string twice
print(text + "Guide") # Concatenate strings
Python uses backslash \ for escaping special characters. To prevent escaping, add an 'r' prefix to denote a raw string.
print('Ru\nnoob') # Output with newline
print(r'Ru\nnoob') # Output with literal backslashes
Note: Python doesn't have a separate character type; a single character is simply a string of length 1.
Lists
Lists are the most commonly used data structures in Python. They can hold elements of different types, including numbers, strings, and even other lists (nested lists).
Lists are written with square brackets [] and elements are separated by commas. Like strings, lists can be indexed and sliced.
The syntax for list slicing is: variable[start_index:end_index]
data = ['abcd', 786, 2.23, 'tutorial', 70.2]
small_data = [123, 'tutorial']
print(data) # Output the entire list
print(data[0]) # Output the first element
print(data[1:3]) # Output from second to third element
print(data[2:]) # Output from third element to end
print(small_data * 2) # Output the list twice
print(data + small_data) # Concatenate lists
Here's an example function to reverse words in a string using list manipulation:
def reverse_words(sentence):
# Split the sentence into words
words = sentence.split(" ")
# Reverse the list of words
# For list [1,2,3,4], list[0]=1, list[1]=2, -1 refers to last element list[-1]=4
# words[-1::-1] has three parameters:
# First parameter -1: last element
# Second parameter: empty, means move to end of list
# Third parameter -1: step size, reverse direction
reversed_words = words[-1::-1]
# Rejoin the words into a string
return ' '.join(reversed_words)
if __name__ == "__main__":
text = 'I enjoy learning Python'
reversed_text = reverse_words(text)
print(reversed_text)
Dictionaries (dict)
Dictionaries are another essential built-in data type in Python. Unlike lists which are ordered collections, dictionaries are unordered collections where elements are accessed via keys rather than offsets.
Dictionaries are mapping types, denoted by curly braces {}. They consist of key-value pairs. Keys must be of immutable types, and within a single dictionary, keys must be unique.
empty_dict = {}
empty_dict['key1'] = "Value 1"
empty_dict[2] = "Value 2"
sample_dict = {'name': 'tutorial', 'code': 1, 'site': 'https://example.com'}
print(empty_dict['key1']) # Output value for 'key1'
print(empty_dict[2]) # Output value for key 2
print(sample_dict) # Output entire dictionary
print(sample_dict.keys()) # Output all keys
print(sample_dict.values()) # Output all values
Boolean Type (bool)
Boolean types have only two values: True and False. They can be compared with other data types like numbers and strings. In comparisons, Python treats True as 1 and False as 0.
Boolean types work with logical operators: and, or, and not. These can combine multiple boolean expressions to produce new boolean values.
Boolean types can be converted to other data types like integers, floats, and strings. When converted, True becomes 1 and False becomes 0.
true_val = True
false_val = False
# Comparison operators
print(2 < 3) # True
print(2 == 3) # False
# Logical operators
print(true_val and false_val) # False
print(true_val or false_val) # True
print(not true_val) # False
# Type conversion
print(int(true_val)) # 1
print(float(false_val)) # 0.0
print(str(true_val)) # "True"
Important: In Python, all non-zero numbers and non-empty strings, lists, tuples, etc. are considered True. Only 0, empty strings, empty lists, empty tuples, etc. are considered False.
Tuples
Tuples are similar to lists, but their elements cannot be modified. Tuples are written in parentheses () with elements separated by commas.
data_tuple = ('abcd', 786, 2.23, 'tutorial', 70.2)
small_tuple = (123, 'tutorial')
print(data_tuple) # Output entire tuple
print(data_tuple[0]) # Output first element
print(data_tuple[1:3]) # Output from second to third element
print(data_tuple[2:]) # Output from third element to end
print(small_tuple * 2) # Output tuple twice
print(data_tuple + small_tuple) # Concatenate tuples
Tuples, like strings, can be indexed with 0-based indexing, and -1 refers to the last element. They can also be sliced.
Strings can be considered a special type of tuple.
sample_tuple = (1, 2, 3, 4, 5, 6)
print(sample_tuple[0]) # 1
print(sample_tuple[1:5]) # (2, 3, 4, 5)
sample_tuple[0] = 11 # This will raise an error
Although tuple elements cannot be changed, tuples can contain mutable objects like lists.
Special syntax is used for tuples with 0 or 1 element:
empty_tuple = () # Empty tuple
single_element = (20,) # Single element requires a comma
Sets
Sets in Python are unordered, mutable data types that store unique elements. They support common set operations like intersection, union, and difference.
Sets are denoted by curly braces {} with elements separated by commas. They can also be created using the set() function.
Note: An empty set must be created with set(), not {}, as {} creates an empty dictionary.
sites = {'Google', 'Baidu', 'Taobao', 'Runoob', 'Facebook', 'Zhihu'}
print(sites) # Output set, duplicate elements are automatically removed
Membership testing:
if 'Runoob' in sites:
print('Runoob is in the set')
else:
print('Runoob is not in the set')
Set operations:
set_a = set('abracadabra')
set_b = set('alacazam')
print(set_a)
print(set_a - set_b) # Difference (elements in a but not in b)
print(set_a | set_b) # Union (elements in either a or b)
print(set_a & set_b) # Intersection (elements common to both a and b)
print(set_a ^ set_b) # Symmetric difference (elements in either a or b but not both)
Program Interaction
In Python3.x, the input() function takes standard input and returns it as a string.
user_input = input("Enter value: ")
print(type(user_input)) # Output: <class 'str'>
Formatted Output
Formatted output involves replacing specific parts of a string with actual values before printing.
This is useful for outputting content with fixed formats, such as personalized messages.
Formatting can be done using placeholders:
- %s: Placeholder for any data type
- %d: Placeholder for integers only
message = 'My name is %s, and I am %d years old'
print(message % ('Alice', 30))