Data · 13
Editing lists
Contains, remove, reverse, swap, fill with one value, copy.
After a list is made you can still take items out and change their order.
The example below keeps a copy of a list of cards, asks whether a number is in it and removes it if so, removes the first card, reverses the list, and swaps the first two cards.
Then it prints the edited list, the copy of the original, and a new list filled with zeros.
n = int(input())cards = list(map(int, input().split()))x = int(input())original = cards.copy() # 복사해 둬요if x in cards: print("yes") cards.remove(x) # 값으로 빼기: 처음 나오는 하나만else: print("no")cards.pop(0) # 자리로 빼기: 0번cards.reverse()cards[0], cards[1] = cards[1], cards[0] # 자리 바꾸기blank = [0] * len(cards) # 0으로 채운 새 목록print(*cards)print(*original)print(*blank)const lines = require("fs").readFileSync(0, "utf8").trim().split("\n");const cards = lines[1].trim().split(/\s+/).map(Number);const x = Number(lines[2]);const original = [...cards]; // 복사해 둬요if (cards.includes(x)) { console.log("yes"); cards.splice(cards.indexOf(x), 1); // 값으로 빼기: 자리를 찾아서 하나만} else { console.log("no");}cards.splice(0, 1); // 자리로 빼기: 0번cards.reverse();[cards[0], cards[1]] = [cards[1], cards[0]]; // 자리 바꾸기const blank = new Array(cards.length).fill(0); // 0으로 채운 새 목록console.log(cards.join(" "));console.log(original.join(" "));console.log(blank.join(" "));import { readFileSync } from "node:fs";const lines: string[] = readFileSync(0, "utf8").trim().split("\n");const cards: number[] = lines[1].trim().split(/\s+/).map(Number);const x: number = Number(lines[2]);const original: number[] = [...cards]; // 복사해 둬요if (cards.includes(x)) { console.log("yes"); cards.splice(cards.indexOf(x), 1); // 값으로 빼기: 자리를 찾아서 하나만} else { console.log("no");}cards.splice(0, 1); // 자리로 빼기: 0번cards.reverse();[cards[0], cards[1]] = [cards[1], cards[0]]; // 자리 바꾸기const blank: number[] = new Array<number>(cards.length).fill(0); // 0으로 채운 새 목록console.log(cards.join(" "));console.log(original.join(" "));console.log(blank.join(" "));import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.Scanner; public class Main { static void show(List<Integer> list) { StringBuilder line = new StringBuilder(); for (int i = 0; i < list.size(); i++) line.append(i > 0 ? " " : "").append(list.get(i)); System.out.println(line); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); List<Integer> cards = new ArrayList<>(); for (int i = 0; i < n; i++) cards.add(sc.nextInt()); int x = sc.nextInt(); List<Integer> original = new ArrayList<>(cards); // 복사해 둬요 if (cards.contains(x)) { System.out.println("yes"); cards.remove(Integer.valueOf(x)); // 값으로 빼기: 처음 나오는 하나만 } else { System.out.println("no"); } cards.remove(0); // 자리로 빼기: 0번 Collections.reverse(cards); Collections.swap(cards, 0, 1); // 자리 바꾸기 List<Integer> blank = new ArrayList<>(Collections.nCopies(cards.size(), 0)); // 0으로 채운 새 목록 show(cards); show(original); show(blank); }}using System;using System.Collections.Generic;using System.Linq; class Program{ static void Main() { int n = int.Parse(Console.ReadLine()); List<int> cards = Console.ReadLine().Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToList(); int x = int.Parse(Console.ReadLine()); List<int> original = new List<int>(cards); // 복사해 둬요 if (cards.Contains(x)) { Console.WriteLine("yes"); cards.Remove(x); // 값으로 빼기: 처음 나오는 하나만 } else { Console.WriteLine("no"); } cards.RemoveAt(0); // 자리로 빼기: 0번 cards.Reverse(); (cards[0], cards[1]) = (cards[1], cards[0]); // 자리 바꾸기 List<int> blank = Enumerable.Repeat(0, cards.Count).ToList(); // 0으로 채운 새 목록 Console.WriteLine(string.Join(" ", cards)); Console.WriteLine(string.Join(" ", original)); Console.WriteLine(string.Join(" ", blank)); }}#include <algorithm>#include <iostream>#include <vector> void show(const std::vector<int>& list) { for (size_t i = 0; i < list.size(); i++) std::cout << (i > 0 ? " " : "") << list[i]; std::cout << '\n';} int main() { int n, x; std::cin >> n; std::vector<int> cards(n); for (int& c : cards) std::cin >> c; std::cin >> x; std::vector<int> original = cards; // 복사해 둬요(vector는 대입하면 복사) auto it = std::find(cards.begin(), cards.end(), x); if (it != cards.end()) { std::cout << "yes\n"; cards.erase(it); // 값으로 빼기: 찾은 자리 하나만 } else { std::cout << "no\n"; } cards.erase(cards.begin()); // 자리로 빼기: 0번 std::reverse(cards.begin(), cards.end()); std::swap(cards[0], cards[1]); // 자리 바꾸기 std::vector<int> blank(cards.size(), 0); // 0으로 채운 새 목록 show(cards); show(original); show(blank);}#include <stdio.h>#include <string.h> void show(const int *list, int n) { for (int i = 0; i < n; i++) printf(i > 0 ? " %d" : "%d", list[i]); printf("\n");} // 자리로 빼기: 뒤의 값들을 한 칸씩 당기고, 줄어든 개수를 돌려줘요int remove_at(int *list, int n, int at) { for (int i = at; i + 1 < n; i++) list[i] = list[i + 1]; return n - 1;} int main(void) { int n, x, cards[1000], original[1000], blank[1000]; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &cards[i]); scanf("%d", &x); int m = n; memcpy(original, cards, n * sizeof cards[0]); // 복사해 둬요 int at = -1; for (int i = 0; i < n && at < 0; i++) if (cards[i] == x) at = i; // 있나: 처음 나오는 자리 찾기 if (at >= 0) { printf("yes\n"); n = remove_at(cards, n, at); // 값으로 빼기 } else { printf("no\n"); } n = remove_at(cards, n, 0); // 자리로 빼기: 0번 for (int i = 0, j = n - 1; i < j; i++, j--) { // 뒤집기: 양 끝에서 맞바꿔요 int t = cards[i]; cards[i] = cards[j]; cards[j] = t; } int t = cards[0]; cards[0] = cards[1]; cards[1] = t; // 자리 바꾸기 for (int i = 0; i < n; i++) blank[i] = 0; // 0으로 채운 새 목록 show(cards, n); show(original, m); show(blank, n); return 0;}n = Console.ReadLine().ToNumber();cards = Console.ReadNumbers();x = Console.ReadLine().ToNumber();original = cards.GetRange(0, cards.Count); // 복사해 둬요if (cards.Contains(x)){ Console.WriteLine("yes"); cards.Remove(x); // 값으로 빼기: 처음 나오는 하나만}else{ Console.WriteLine("no");}cards.RemoveAt(0); // 자리로 빼기: 0번cards.Reverse();t = cards[0]; // 자리 바꾸기cards[0] = cards[1];cards[1] = t;blank = NewList(cards.Count, 0); // 0으로 채운 새 목록Console.WriteLine(cards);Console.WriteLine(original);Console.WriteLine(blank);5 30 10 40 10 50 10
yes 10 50 40 30 10 40 10 50 0 0 0
Key points
- Asking whether a value is in the list answers true or false.
You can write it in one line instead of comparing in a loop (in C you search with a loop). - Removing comes in two kinds.
By position deletes slot i; by value deletes only the first slot holding that value.
Either way the items after it move one slot forward.
What happens when the value is not there differs by language. - Reversing turns the order of that same list around; it does not make a new list.
- Swapping: if you start with
a[0] = a[1], the old value ofa[0]is gone.
Move one value into a temporary variable first, or use the syntax that swaps both at once. - Filling with one value: make a list from just a size and a starting value, such as a list of n zeros.
- Copying: lesson 08 said
b = aonly gives the same list a second name.
To keep the original, make a separate copy before you edit.
In Python, JavaScript, Java, C# and Craykon this copy goes only one level deep: copy a grid (a list of lists, lesson 12) and the rows are still shared, so copy each row separately.
How each language writes it
| Python | x in a.By value a.remove(x) (ValueError if missing), by position a.pop(i) or del a[i].a.reverse().a[0], a[1] = a[1], a[0].[0] * n.Copy: a.copy() |
|---|---|
| JavaScript | a.includes(x).By position a.splice(i, 1).There is no remove-by-value, so find the position with a.indexOf(x) and splice it.a.reverse().[a[0], a[1]] = [a[1], a[0]].new Array(n).fill(0).Copy: [...a] |
| TypeScript | Same as JavaScript |
| Java | On a List<Integer>: a.contains(x).By position a.remove(i), by value a.remove(Integer.valueOf(x)) (false if missing).Collections.reverse(a), Collections.swap(a, 0, 1).new ArrayList<>(Collections.nCopies(n, 0)).Copy: new ArrayList<>(a).An array new int[n] starts filled with zeros |
| C# | On a List<int>: a.Contains(x).By value a.Remove(x) (false if missing), by position a.RemoveAt(i).a.Reverse().(a[0], a[1]) = (a[1], a[0]).Enumerable.Repeat(0, n).ToList().Copy: new List<int>(a) |
| C++ | The value is there if std::find(a.begin(), a.end(), x) is not a.end().Remove the found position with a.erase(it), or slot i with a.erase(a.begin() + i).std::reverse(a.begin(), a.end()), std::swap(a[0], a[1]).std::vector<int> b(n, 0).b = a is itself a copy |
| C | Arrays have a fixed size and none of these functions. Search with a loop; to remove, shift the later items one slot forward and reduce the count yourself. Reverse by swapping from both ends, and swap with a temporary variable t.Copy with memcpy(b, a, n * sizeof a[0]) — b = a is a compile error |
| Craykon | a.Contains(x).By value a.Remove(x) (false if missing), by position a.RemoveAt(i).a.Reverse().Swap with a temporary variable. NewList(n, 0).Copy: a.GetRange(0, a.Count) |
Common mistakes
Removing a value that is not there removed the last itemJavaScript · TypeScript
const a = [1, 2, 3];
a.splice(a.indexOf(9), 1);
console.log(a);→ [ 1, 2 ] — when the value is missing indexOf gives -1, and splice(-1, 1) removes the last slot
Check first: const i = a.indexOf(9); if (i !== -1) a.splice(i, 1);
Removing from a list while looping over itPython · JavaScript · TypeScript · Java · C#
a = [1, 1, 2, 3]
for v in a:
if v == 1:
a.remove(v)
print(a)→ Python prints [1, 2, 3] — the next item moves into the removed slot, so the second 1 is skipped. JavaScript's for...of gives the same result. Java stops with ConcurrentModificationException and C# with InvalidOperationException. Only Craykon's foreach walks a snapshot taken when the loop starts, so both 1s are removed and the list is 2 3
Build a new list of the items to keep, or use the dedicated function: Python a = [v for v in a if v != 1], JavaScript a = a.filter(v => v !== 1), Java a.removeIf(v -> v == 1), C# a.RemoveAll(v => v == 1).
Meant to remove the value 1, but slot 1 was removedJava
List<Integer> a = new ArrayList<>(List.of(1, 2, 3));
a.remove(1);
System.out.println(a);→ [1, 3] — given an int, it removes by position. The 2 in slot 1 is gone
To remove by value write a.remove(Integer.valueOf(1)) → [2, 3].
On [10, 20, 30], a.remove(10) looks for slot 10 and stops with IndexOutOfBoundsException.
Reversing is a command that changes the list itself, so in some languages you must not use its result.
In Python, after
b = a.reverse(), b is None.When you need a new reversed list, use
a[::-1] in Python or, in JavaScript, copy and then reverse: [...a].reverse().And in C,
int *b = a; is not a copy but another name pointing at the same array: after b[0] = 9, a[0] is 9 too.