📚

Understanding String and List Concatenation in Python

Oct 25, 2024

Lecture on String and List Concatenation in Python

Overview

  • Concatenation involves combining two entities (strings or lists) into a new one.
  • The + operator is used for concatenation.

String Concatenation

  • Concatenating strings combines them into a new string.
    • Example: 'abc' + 'def' results in 'abcdef'.

List Concatenation

  • Works similarly to string concatenation.
  • Combines two lists into a new list.
    • Example: [a, b] + [c, d] results in [a, b, c, d].

Key Points

  • Single Data Type: You can only concatenate lists with lists.
  • Type Error: Concatenating a list with a non-list (e.g., integer) causes a Type Error.
    • Solution: Enclose the non-list in a literal list.
      • Example: alist + [5] (not alist + 5).
  • Immutable Original Lists: Concatenation does not alter the original lists.
    • The original lists remain unchanged.
    • The result of concatenation is a new list.

Examples and Experimentation

  • Creating Lists:

    • List A: [ ]
    • List B: [ ]
    • List C created by concatenating A and B: C = A + B
    • Observation: A and B remain unchanged, C contains elements of A followed by B.
  • Appending Elements:

    • Direct concatenation of non-list element causes error.
    • Enclosing the element in a list is necessary.
      • C + ['d'] creates a new list with 'd' appended.
    • The variable must be reassigned to the new list.

References and Modifications

  • Variable Reference: Multiple variables can reference the same list.

    • Example: D = C (C and D reference the same list).
  • Effect of Modifications:

    • Changing an element in C affects D since both reference the same list.
    • Concatenating a new list changes C's reference, not D's.
    • Example: After C = C + ['7'], C changes but D still references the original list.

Conclusion

  • Concatenation yields new lists without modifying the originals.
  • Variable references determine whether changes affect multiple variables.
  • Experimentation in Python interpreter is encouraged to understand list behavior.