Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

Lists and Strings

In Python, lists and strings share some similarities, but they also have distinct behaviors. Both support indexing, slicing, and iteration, but while lists are mutable (modifiable), strings are immutable (cannot be changed after creation). Understanding their relationship helps in processing text data efficiently.


Lists and Strings Similarities

  • Indexing: Both lists and strings allow accessing individual elements using their index.
  • Slicing: You can extract a portion of a string or list using slicing.
  • Iteration: You can loop through the characters of a string or elements of a list using for loops.

Example:

my_list = ['a', 'b', 'c', 'd']
my_string = "abcd"

print(my_list[1])  # Output: 'b'
print(my_string[1])  # Output: 'b'

Lists and Strings Differences

Feature Lists Strings
Mutability Lists are mutable Strings are immutable
Modification Elements can be changed Cannot modify individual characters
Concatenation list1 + list2 joins lists "Hello" + "World" joins strings
Iteration Iterate over elements Iterate over characters

Example:

# Lists are mutable
my_list = ['h', 'e', 'l', 'l', 'o']
my_list[0] = 'H'
print(my_list)  # Output: ['H', 'e', 'l', 'l', 'o']

# Strings are immutable
my_string = "hello"
# my_string[0] = 'H'  # This will cause an error!

Converting Between Lists and Strings

You can convert a string into a list and vice versa using the list() and join() methods.

String to List

text = "hello"
char_list = list(text)
print(char_list)  # Output: ['h', 'e', 'l', 'l', 'o']

List to String

words = ['Hello', 'World']
sentence = " ".join(words)
print(sentence)  # Output: "Hello World"

Exercise: Try It Yourself!

  1. What will be the output of the following code?

    word = "Python"
    print(list(word))
    • a) ['P', 'y', 't', 'h', 'o', 'n']
    • b) "Python"
    • c) ["Python"]
    • d) Error
  2. Convert the list ['P', 'y', 't', 'h', 'o', 'n'] back into a string "Python" using .join().